如何用按钮绘制多个类别的条形图?

问题描述 投票:0回答:1

对于给定的数据框,我试图创建

plotly
绘制比较条形图,其中
q1,q2..
在 x 轴上,每个
stockname
的条线和 y 轴上的数字。

此外,按钮应该有

[Sales, Net Profit]
选择器,这样当选择一个选项时,它应该绘制这些股票的比较图(最大
6
股票)。

import pandas as pd
import numpy as np
import plotly.graph_objects as go

my_dict = dict({
    'quarterly_result' : ['Sales','Net Profit', 'Sales', 'Net Profit'],
    'stockname' : ['Stock1', 'Stock1','Stock2', 'Stock2'],
    'q1' : [100,10,np.nan,np.nan],
    'q2' : [110,20.6,570,120],
    'q3' : [67,-2.0,620,125.7],
    'q4' : [125,40.5,np.nan,np.nan],
    'q5' : [np.nan,np.nan,660,105.9],
    'q6' : [np.nan,np.nan,636,140]
})

df = pd.DataFrame(my_dict)

fig = go.Figure()

x = df.columns[2:]
y1 = df.loc[0][2:]
y2 = df.loc[2][2:]

fig.add_traces(go.Bar(x=x, y=y1))
fig.add_traces(go.Bar(x=x, y=y2))

buttons = [{'method': 'update', 'label': col, 'args': [{'y': [df[col]]}]} 
           for col in df.iloc[:, 1:]]

updatemenus = [{'buttons': buttons,
                'direction': 'down',
                'showactive': True,}]

# update layout with buttons, and show the figure
fig.update_layout(updatemenus=updatemenus)
fig.show()

我不确定如何绘制这个多类别数据框。下面的代码片段不起作用。我该如何解决这个问题?

错误结果:

enter image description here

预期:

enter image description here

python plotly
1个回答
0
投票

您可以使用各自的指标为每只股票添加轨迹。然后添加按钮以在指标之间切换:

import pandas as pd
import numpy as np
import plotly.graph_objects as go

my_dict = {
    'quarterly_result': ['Sales', 'Net Profit', 'Sales', 'Net Profit'],
    'stockname': ['Stock1', 'Stock1', 'Stock2', 'Stock2'],
    'q1': [100, 10, np.nan, np.nan],
    'q2': [110, 20.6, 570, 120],
    'q3': [67, -2.0, 620, 125.7],
    'q4': [125, 40.5, np.nan, np.nan],
    'q5': [np.nan, np.nan, 660, 105.9],
    'q6': [np.nan, np.nan, 636, 140]
}

df = pd.DataFrame(my_dict)

fig = go.Figure()

# List of quarters
x = df.columns[2:]

# Add traces for each metric
for result in df['quarterly_result'].unique():
    for stock in df['stockname'].unique():
        fig.add_trace(go.Bar(
            x=x,
            y=df[(df['stockname'] == stock) & (df['quarterly_result'] == result)].iloc[0, 2:],
            name=f'{stock} {result}'
        ))

# Add buttons to toggle the visibility
buttons = [{'label': label, 'method': 'update',
            'args': [{'visible': [True if label == i else False for i in df['quarterly_result']]}]}
           for label in df['quarterly_result'].unique()]

updatemenus = [{'buttons': buttons,
                'direction': "down",
                'showactive': True, }]

# update layout with buttons, and show the figure
fig.update_layout(updatemenus=updatemenus)
fig.show()

结果:

初始图,两者都可见: Sales and NP plot

销售: Sales plot

净利润: Net profit plot

© www.soinside.com 2019 - 2024. All rights reserved.