简体   繁体   English

Plotly Stacked Bar Chart 文本注释问题

[英]Plotly Stacked Bar Chart text annotation issue

So, I have this simplified data frame and I'm using plotly.graph_objects to plot a stacked bar chart with text annotations.所以,我有这个简化的数据框,我使用plotly.graph_objects绘制带有文本注释的堆积条形图。 I got the text as I wanted from the Salary column but I can't get the same for the Age column where the values are significantly lower.我从 Salary 列中得到了我想要的文本,但是对于 Age 列中的值明显较低的情况,我无法得到相同的文本。 I would like these annotations to be the same size and on top of each bar.我希望这些注释的大小相同并位于每个条形图的顶部。 How can I get the text annotations to be visible for the Age column as well?我怎样才能让年龄列的文本注释也可见?

Please find my code below:请在下面找到我的代码:

data = {'Name':['Tom', 'Nick', 'Jack'],
        'Age':[18, 21, 19],
        'Salary':[500, 700, 900]}
df_new=pd.DataFrame(data)

fig = go.Figure(go.Bar(x = df_new["Name"],
                       y = df_new["Age"],name='Age',text=df_new["Age"],
                       textposition='outside'))
fig.add_bar(x = df_new["Name"],
            y = df_new["Salary"],name='Salary',text=df_new["Salary"],
            textposition='outside')
fig.update_layout(barmode='stack',
                  title = 'Age - Salary',
                  xaxis_title="Name",
                  yaxis_title="Age / Salary")

在此处输入图片说明

Thanks in advance!提前致谢!

I think you have to choose from 2 possible solutions.我认为您必须从 2 种可能的解决方案中进行选择。 First of all, by using the barmode = stack argument, you are stacking and thus summing the values of age and salary.首先,通过使用barmode = stack参数,您正在堆叠并因此对年龄和薪水的值求和。 The height of bars will be age + salary , such that the height of Tom's bar will be 500 + 18 = 518 .条形的高度将为age + salary ,这样 Tom 的条形的高度将为500 + 18 = 518 I'd advise against this, as the height should reflect the callout value in my opinion.我建议不要这样做,因为在我看来,高度应该反映标注值。


Solution 1 - grouped bars解决方案 1 - 分组条

This solution is based on changing the barmode to barmode = group .此解决方案基于将 barmode 更改为barmode = group This will make two separate bars, which have their own callout and heights reflecting their values.这将制作两个独立的条形,它们有自己的标注和高度来反映它们的值。 I've also added the width argument to make prettier aspect ratios.我还添加了width参数来制作更漂亮的纵横比。

fig = go.Figure()
fig.add_bar(x = df_new["Name"],
            y = df_new["Age"],name='Age',text=df_new["Age"],
            width = [0.3]*len(df_new),
            )

fig.add_bar(x = df_new["Name"],
            y = df_new["Salary"],name='Salary',text=df_new["Salary"],
            width = [0.3]*len(df_new)
            )
fig.update_layout(barmode='group',
                  title = 'Age - Salary',
                  xaxis_title="Name",
                  yaxis_title="Age / Salary"
                  )
fig.update_traces(
    textposition='outside'
)
fig.update_yaxes(range=[0,1000])

Solution 2 - add secondary y-axis解决方案 2 - 添加辅助 y 轴

I prefer this solution, as the relative size of the two categories can each be scaled to their own domain;我更喜欢这个解决方案,因为这两个类别的相对大小可以分别扩展到它们自己的领域; which makes the chart a lot more readable.这使得图表更具可读性。 This uses make_subplots to create two axes and the secondary_y argument.这使用make_subplots创建两个轴和secondary_y参数。 I've made both bars visible by playing around with the widths and ranges of the axes.我通过调整轴的宽度和范围使两个条都可见。

Based on the data you'd have to manually rescale to your liking.根据数据,您必须根据自己的喜好手动重新缩放。 You could also incorporate opacity for look-through bars, but you'd still have the risk of overlapping data callouts.您还可以为透视条添加opacity ,但仍然存在数据标注重叠的风险。

from plotly.subplots import make_subplots

fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_bar(
    x=df_new["Name"],
    y=df_new["Age"],
    name="Age",
    text=df_new["Age"],
    width=[0.3] * len(df_new),
    secondary_y=True,
    textposition="outside"
)
fig.add_bar(
    x=df_new["Name"],
    y=df_new["Salary"],
    name="Salary",
    text=df_new["Salary"],
    width=[0.5] * len(df_new),
    secondary_y=False,
    textposition="outside"
)

fig.update_yaxes(range=[0, 1000], title='Salary', secondary_y=False)
fig.update_yaxes(range=[0, 45], title='Age', secondary_y=True)
fig.update_layout(title="Age and Salary", xaxis_title="Name")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM