gpt4 book ai didi

python - Plotly:将多个图形绘制为子图

转载 作者:太空狗 更新时间:2023-10-29 22:06:20 25 4
gpt4 key购买 nike

这些资源展示了如何从单个 Pandas DataFrame 中获取数据并在 Plotly 图表上绘制不同列的子图。我有兴趣从单独的 DataFrame 创建图形并将它们绘制到与子图相同的图形中。这对 Plotly 来说可能吗?

https://plot.ly/python/subplots/

https://plot.ly/pandas/subplots/

我正在从这样的数据框中创建每个图形:

import pandas as pd
import cufflinks as cf
from plotly.offline import download_plotlyjs, plot,iplot
cf.go_offline()

fig1 = df.iplot(kind='bar',barmode='stack',x='Type',
y=mylist,asFigure=True)

编辑:下面是一个基于 Naren 反馈的示例:

创建数据框:

a={'catagory':['loc1','loc2','loc3'],'dogs':[1,5,6],'cats':[3,1,4],'birds':[4,12,2]}
df1 = pd.DataFrame(a)
b={'catagory':['loc1','loc2','loc3'],'dogs':[12,3,5],'cats':[4,6,1],'birds':[7,0,8]}
df2 = pd.DataFrame(b)

该图将只显示狗的信息,而不是鸟或猫的信息:

fig = tls.make_subplots(rows=2, cols=1)

fig1 = df1.iplot(kind='bar',barmode='stack',x='catagory',
y=['dogs','cats','birds'],asFigure=True)

fig.append_trace(fig1['data'][0], 1, 1)

fig2 = df2.iplot(kind='bar',barmode='stack',x='catagory',
y=['dogs','cats','birds'],asFigure=True)

fig.append_trace(fig2['data'][0], 2, 1)

iplot(fig)

Just the dogs are shown, not the cats or birds:

最佳答案

这是一个工作示例中的简短函数,用于将图形列表全部保存到单个 HTML 文件中。

def figures_to_html(figs, filename="dashboard.html"):
with open(filename, 'w') as dashboard:
dashboard.write("<html><head></head><body>" + "\n")
for fig in figs:
inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]
dashboard.write(inner_html)
dashboard.write("</body></html>" + "\n")


# Example figures
import plotly.express as px
gapminder = px.data.gapminder().query("country=='Canada'")
fig1 = px.line(gapminder, x="year", y="lifeExp", title='Life expectancy in Canada')
gapminder = px.data.gapminder().query("continent=='Oceania'")
fig2 = px.line(gapminder, x="year", y="lifeExp", color='country')
gapminder = px.data.gapminder().query("continent != 'Asia'")
fig3 = px.line(gapminder, x="year", y="lifeExp", color="continent",
line_group="country", hover_name="country")

figures_to_html([fig1, fig2, fig3])

enter image description here

关于python - Plotly:将多个图形绘制为子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com