python - 使用 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')
谢谢,
解决方案
您可以使用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 中获得它,您需要从回调中返回上述内容。
推荐阅读
- r - 无论如何要改变R(geom_point)中ggplot中值的大小?
- javascript - 如何在不显示在网站上的情况下从 html 为 php 赋予特殊字符?
- java - 将 Spring Boot 与 MySQL 数据库一起使用的问题
- powerapps - 使用 CDS 中的实体过滤 PowerApps 中的库
- javascript - 我在设置 javascript cron 时遇到问题
- ruby-on-rails - 从 Rails 中的 ActiveRecord::AssociationRelation 获取不同的值
- database - 为什么保留重复记录时h2复合主键不起作用?
- django - 如何在 Django 中使用 TinyMCE 5?
- python - seaboarn散点图中的预定义点颜色
- visual-studio - 如何在c#中声明全局变量