[英]How to add a Pie chart and grouped Bar chart on plotly express subplots
[英]How to label a grouped bar chart using plotly express?
我想在 plotly express 中将数据标签添加到条形图的顶部。 我正在使用数据框中的两个不同列,所以我不能使用“颜色”方法。 我想为每个栏定义“文本”,以便在栏顶部显示数据。 这是一个MRE。
import pandas as pd
import plotly.express as px
x = ['Aaron', 'Bob', 'Chris']
y1 = [5, 10, 6]
y2 = [8, 16, 12]
fig = px.bar(x=x, y=[y1,y2],barmode='group')
fig.show()
我试过了:
fig = px.bar(x=x, y=[y1,y2],text=[y1,y2], barmode='group')
但这不起作用。
使用您的设置,只需将以下内容添加到组合中:
texts = [y1, y2]
for i, t in enumerate(texts):
fig.data[i].text = t
fig.data[i].textposition = 'outside'
import pandas as pd
import plotly.express as px
x = ['Aaron', 'Bob', 'Chris']
y1 = [5, 10, 6]
y2 = [8, 16, 12]
fig = px.bar(x=x, y=[y1,y2],barmode='group')
texts = [y1, y2]
for i, t in enumerate(texts):
fig.data[i].text = t
fig.data[i].textposition = 'outside'
fig.show()
我找到了一个更好的答案。
让我们以这本字典为例:
data_dictionary = {
"data_frame":{
"x":["Aaron", "Bob", "Chris"],
"y1":[5, 10, 6],
"y2":[8, 16, 12]
},
"x":"x",
"y":["y1", "y2"],
"barmode":"group",
"text":None,
"text_auto":True
}
之后,让我们创建一个图形:
fig = px.bar(
**data_dictionary
)
如果您fig.show()
,您将看到一个类似于vestland 的图表的图表。
您唯一需要做的就是将 text 设置为 None 并将 text_auto 设置为 True。
我希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.