Open6
Personal Plotly tips
color (legend) のラベルから = を取り除く
Before
After
import pandas as pd
import plotly.express as px
data = pd.DataFrame(
{
'x': ['x1', 'x2', 'x3', 'x4'],
'y': [1, 2, 3, 4],
'z': ['z1', 'z1', 'z2', 'z2']
}
)
fig = px.bar(
data_frame = data,
x = 'x',
y = 'y',
color = 'z'
)
fig.for_each_trace(
lambda trace: trace.update(
dict(
name = trace.name.split('=')[1]
)
)
)
fig.show()
線の太さを変える
Before
After
import pandas as pd
import plotly.express as px
LINE_WIDTH = 10
data = pd.DataFrame(
{
'x': [1, 5],
'y': [1, 5]
}
)
fig = px.line(
data_frame = data,
x = 'x',
y = 'y'
)
fig.update_traces(
line = dict(
width = LINE_WIDTH
)
)
fig.show()
colorごとに線の太さを変える
Before
After
import pandas as pd
import plotly.express as px
data = pd.DataFrame(
{
'x': [1, 5, 1, 5],
'y': [1, 5, 2, 6],
'z': ['z1', 'z1', 'z2', 'z2']
}
)
color2linewidth = dict(
z1 = 2,
z2 = 10
)
fig = px.line(
data_frame = data,
x = 'x',
y = 'y',
color = 'z'
)
fig.for_each_trace(
lambda trace: trace.update(
line = dict(
width = color2linewidth[trace.name.split('=')[1]]
)
)
)
fig.show()
折線にマーカーをつける
Before
After
import pandas as pd
import plotly.express as px
data = pd.DataFrame(
{
'x': [1, 3, 5],
'y': [1, 5, 3]
}
)
fig = px.line(
data_frame = data,
x = 'x',
y = 'y'
)
fig.update_traces(
mode = 'lines+markers'
)
fig.show()
マーカのサイズを変える
Before
After
import pandas as pd
import plotly.express as px
MARKER_SIZE = 10
data = pd.DataFrame(
{
'x': [1, 3, 5],
'y': [1, 5, 3]
}
)
fig = px.line(
data_frame = data,
x = 'x',
y = 'y'
)
fig.update_traces(
mode = 'lines+markers',
marker = dict(
size = MARKER_SIZE
)
)
fig.show()
Google Colabratory で グラフを保存する
Library の update
!pip install -U kaleido
!pip install -U plotly
グラフを保存する
import plotly.express as px
SAVE_PATH = "./"
data = pd.DataFrame(
{
"x": [1, 2, 3],
"y": [1, 3, 5],
}
)
fig = px.line(
data_frame=data,
x="x",
y="y",
)
fig.write_image(
SAVE_PATH + "graph.png",
width=1600,
height=800,
zoom=10
)
x軸, y軸, Legend のフォントサイズを変更する
import plotly.express as px
import pandas as pd
AXIS_TITLE_SIZE = 15
TICKS_SIZE = 10
LEGEND_SIZE = 15
data = pd.DataFrame(
{
"x": [1, 2, 3],
"y": [1, 3, 5],
}
)
fig = px.line(
data_frame=data,
x="x",
y="y",
)
fig.update_layout(
xaxis=dict(titlefont=dict(size=AXIS_TITLE_SIZE), tickfont=dict(size=TICKS_SIZE)),
yaxis=dict(titlefont=dict(size=AXIS_TITLE_SIZE), tickfont=dict(size=TICKS_SIZE)),
legend = dict(font = dict(size=LEGEND_SIZE))
)