如何在Plotly Express的直方图中去除分面标题的列名
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
"country": ['Poland', 'Poland', 'Poland',
'Germany', 'Germany', 'Germany',
'France', 'France', 'France'],
"city": ['Warsaw', 'Krakow', 'Gdansk',
'Berlin', 'Munich', 'Nuremberg',
'Paris', 'Marseille', 'Brest'],
"population": [1863000, 803000, 470000,
3769000, 1488000, 518000,
2103000, 877000, 140000]
})
px.histogram(df,
x="population",
facet_col="country",
labels={"population": "Population"},
title="Areas per country")
使用 facet_col 时,Plotly Express会默认把列名添加到每个分面标题上,例如 "country=Poland"。
如何去掉 "country=" 这一部分,只显示 "Poland"?
解决方案
好吧,在查看代码之后,facet_col 的标题默认包含列名,但你可以用 for_each_annotation 对它们进行整理,代码中可以这样使用:
fig = px.histogram(df,
x="population",
facet_col="country",
labels={"population": "Population"},
title="Areas per country")
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()
这会把注释文本按 = 拆分,只保留其后面的值,因此 "country=Poland" 变成只有 "Poland"。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。