【发布时间】:2020-12-02 19:25:49
【问题描述】:
有没有一种简单的方法可以使用 plotly express 隐藏多面图中的重复轴标题?我试过设置
visible=True
在下面的代码中,但这也隐藏了 y 轴刻度标签(值)。理想情况下,我想将隐藏重复的轴标题设置为一般多面图的默认设置(或者甚至更好,只是默认为整个多面图显示单个 x 和 y 轴标题。
这里是测试代码:
import pandas as pd
import numpy as np
import plotly.express as px
import string
# create a dataframe
cols = list(string.ascii_letters)
n = 50
df = pd.DataFrame({'Date': pd.date_range('2021-01-01', periods=n)})
# create data with vastly different ranges
for col in cols:
start = np.random.choice([1, 10, 100, 1000, 100000])
s = np.random.normal(loc=0, scale=0.01*start, size=n)
df[col] = start + s.cumsum()
# melt data columns from wide to long
dfm = df.melt("Date")
fig = px.line(
data_frame=dfm,
x = 'Date',
y = 'value',
facet_col = 'variable',
facet_col_wrap=6,
facet_col_spacing=0.05,
facet_row_spacing=0.035,
height = 1000,
width = 1000,
title = 'Value vs. Date'
)
fig.update_yaxes(matches=None, showticklabels=True, visible=True)
fig.update_annotations(font=dict(size=16))
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
最终代码(已接受的答案)。注意情节 >= 4.9
import pandas as pd
import numpy as np
import plotly.express as px
import string
import plotly.graph_objects as go
# create a dataframe
cols = list(string.ascii_letters)
n = 50
df = pd.DataFrame({'Date': pd.date_range('2021-01-01', periods=n)})
# create data with vastly different ranges
for col in cols:
start = np.random.choice([1, 10, 100, 1000, 100000])
s = np.random.normal(loc=0, scale=0.01*start, size=n)
df[col] = start + s.cumsum()
# melt data columns from wide to long
dfm = df.melt("Date")
fig = px.line(
data_frame=dfm,
x = 'Date',
y = 'value',
facet_col = 'variable',
facet_col_wrap=6,
facet_col_spacing=0.05,
facet_row_spacing=0.035,
height = 1000,
width = 1000,
title = 'Value vs. Date'
)
fig.update_yaxes(matches=None, showticklabels=True, visible=True)
fig.update_annotations(font=dict(size=16))
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
# hide subplot y-axis titles and x-axis titles
for axis in fig.layout:
if type(fig.layout[axis]) == go.layout.YAxis:
fig.layout[axis].title.text = ''
if type(fig.layout[axis]) == go.layout.XAxis:
fig.layout[axis].title.text = ''
# keep all other annotations and add single y-axis and x-axis title:
fig.update_layout(
# keep the original annotations and add a list of new annotations:
annotations = list(fig.layout.annotations) +
[go.layout.Annotation(
x=-0.07,
y=0.5,
font=dict(
size=16, color = 'blue'
),
showarrow=False,
text="single y-axis title",
textangle=-90,
xref="paper",
yref="paper"
)
] +
[go.layout.Annotation(
x=0.5,
y=-0.08,
font=dict(
size=16, color = 'blue'
),
showarrow=False,
text="Dates",
textangle=-0,
xref="paper",
yref="paper"
)
]
)
fig.show()
【问题讨论】:
标签: python express plotly facet axis-labels