首页 > 解决方案 > 使用 Dash/Plotly 在折线图上绘制多列

问题描述

我有一张看起来像这样的桌子......

ticker,price1y,price2y,price3y,price5y,
aapl,12,23,47,69,
tsla,-9,24,54,190,
att,-10,23,34,35,

我想用大熊猫在破折号中绘制这些以显示 price1y price2y ... price5y 沿 x 轴和 % 沿 y 轴变化。我需要能够使用破折号的回调功能选择多个值以添加到图表中。

我目前创建了一个 dash_core_components 图表,但是我没有成功地绘制这个图表。

app.layout = html.Div([
        html.Div([
                     dcc.Graph(
                        id='bar-graph'

                        )
            ], className='twelve columns')

谢谢,

标签: pythonmatplotlibplotlyplotly-dash

解决方案


您可以使用plotly 中的分组条形图

做进口:

import plotly.plotly as py
import plotly.graph_objs as go

示例数据框:

data = {
    'ticker': ['aapl', 'tsla', 'att'],
    'price1y': [12 ,-9 ,-10],
    'price2y': [23 ,24 ,23],
    'price3y': [47 ,54 ,34],
    'price5y': [69 ,190 ,35]
}
df = pd.DataFrame(data).set_index('ticker')

好像:

        price1y price2y price3y price5y
ticker              
aapl      12    23        47    69
tsla      -9    24        54    190
att      -10    23        34    35

然后您可以遍历列为分组条形图动态创建数据

res = []
for col in df.columns:
    res.append(
        go.Bar(
            x=df.index.values.tolist(),
            y=df[col].values.tolist(),
            name=col
        )
    )

layout = go.Layout(
    barmode='group'
)

fig = go.Figure(data=res, layout=layout)
py.iplot(fig, filename='grouped-bar')

这将产生:

在此处输入图像描述

为了在 Dash 中获得它,您需要从回调中返回上述内容。


推荐阅读