【问题标题】:Python Plotly bar's width with categorical axes when using a loop for使用循环时Python Plotly栏的宽度与分类轴
【发布时间】:2022-01-17 23:38:54
【问题描述】:

我有一个关于 plotly 的问题,我尝试创建一个带有分类轴的条形图,但是当显示多个类别时,条形的宽度会大大减小。

代码:

ar = np.array([[0.88, 0.55,0.66,0.87,0.88,0.45,0.56,0.54,0.29,0.45,0.58,0.78], [0.56, 0.59,0.48,0.55,0.45,0.74,0.54,0.56,0.89,0.45,0.56,0.87]])
df = pd.DataFrame(ar, index = ['fight1', 'fight2'], 
                  columns = ['Str. Acc. R1','Str. Acc. R2','Str. Acc. R3',
                             'Str. Acc. opp R1','Str. Acc. opp R2','Str. Acc. opp R3',
                             'TD. Acc. R1', 'TD. Acc. R2','TD. Acc. R3',
                             'TD. Acc. opp R1','TD. Acc. opp R2','TD. Acc. opp R3'])

fig = go.Figure()

dico_SLSA={"Str. Acc." : [col for col in df.columns if "Str." in col],
           "TD. Acc.": [col for col in df.columns if "TD." in col]}

stat = ["Str. Acc."]
##stat = ["Str. Acc.", "TD. Acc."]

for item in stat:
    
    axesx = [["R"+str(i) for i in range(1,4)],[item]*3]
    
    selected_cols = dico_SLSA.get(item)
    selected_cols1 = [col for col in selected_cols if "opp" not in col]
    selected_cols2 = [col for col in selected_cols if "opp" in col]

    fig.add_trace(go.Bar(x = axesx,
                         y = df[selected_cols1].values.tolist()[0],
                         name = item))

    fig.add_trace(go.Bar(x = axesx,
                         y = df[selected_cols2].values.tolist()[0],
                         name = item+"_Opp"))



fig.show()

使用 stat=["Str. Acc."] 条的粗细是正确的,但是如果我们选择 stat=["Str. Acc.","TD. Acc."] 条的粗细会大大减小。

1 个类别:

Display with 1 category

2 个类别:

Display with 2 categories

欲望展示:

Desire display

我需要保留 for 循环,因为我将此图表与破折号一起使用,并且有一个下拉菜单可以选择 stat 中的数据。

谢谢

【问题讨论】:

  • 不确定但试试这个fig.update_traces(width=width)。检查这个link
  • 感谢您的评论,遗憾的是修改宽度无法正常工作,条形重叠。

标签: python plotly plotly-dash figure


【解决方案1】:

我刚刚找到了解决方案,我们必须在trace中添加offsetgroup才能解决问题。如下:

fig.add_trace(go.Bar(x = axesx,
                     y = df[selected_cols1].values.tolist()[0],
                     name = item,
                     offsetgroup = 0))
fig.add_trace(go.Bar(x = axesx,
                     y = df[selected_cols2].values.tolist()[0],
                     name = item+"_Opp",
                     offsetgroup = 1))

祝你有美好的一天!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2020-12-15
    • 2022-01-12
    相关资源
    最近更新 更多