Mic*_*sLE 6 python graph plotly plotly-express
我正在学习使用 pyplot.express 并努力解决以下设计问题:在多面图中,每个子图的轴标题都会重复(在示例中为“花瓣宽度 (cm)”)。有没有办法使用 pyplot.express 为分面图上的所有子图获取单轴标签?
谢谢,迈克尔
最小的例子:
from sklearn.datasets import load_iris
import plotly.express as px
import pandas as pd
import numpy as np
# import iris-data
iris = load_iris()
df= pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
# plot using pyplot.express
fig = px.bar(df, x="sepal length (cm)", y="petal width (cm)", color = 'petal length (cm)', facet_row="species")
fig.show()
Run Code Online (Sandbox Code Playgroud)
ves*_*and 13
对于这种特殊情况,在示例片段之后,只需运行
fig['layout']['yaxis']['title']['text']=''
fig['layout']['yaxis3']['title']['text']=''
fig.show()
Run Code Online (Sandbox Code Playgroud)
或者,对于多个子图的更通用方法,只需运行:
fig.for_each_yaxis(lambda y: y.update(title = ''))
# and:
fig.add_annotation(x=-0.1,y=0.5,
text="Custom y-axis title", textangle=-90,
xref="paper", yref="paper")
Run Code Online (Sandbox Code Playgroud)
我还为所有使用的 y 轴添加了标题fig.add_annotation(),并通过指定确保它始终放置在绘图的中心 yref="paper"
阴谋:
感谢@vestland 帮了大忙!
我根据您的回答想出了一种更灵活的设计(多个 facet_rows)的方法:
首先,我需要删除所有子图轴:
for axis in fig.layout:
if type(fig.layout[axis]) == go.layout.YAxis:
fig.layout[axis].title.text = ''
Run Code Online (Sandbox Code Playgroud)
下一步是添加注释而不是轴,因为布局中的 yaxis 属性总是修改轴之一的缩放比例并弄乱绘图。搜索注释,我找到了如何添加自定义轴的链接。xref='paper'和yref='paper'需要独立于子图定位标签。
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=14
),
showarrow=False,
text="Custom y-axis title",
textangle=-90,
xref="paper",
yref="paper"
)
]
)
Run Code Online (Sandbox Code Playgroud)