Plotly:将多个数字绘制为子图

spa*_*row 7 python plotly

这些资源显示如何从单个Pandas DataFrame中获取数据,并在Plotly图上绘制不同的列子图.我有兴趣从单独的DataFrames创建数字,并将它们绘制为与子图相同的图形.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)
Run Code Online (Sandbox Code Playgroud)

编辑:以下是基于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)
Run Code Online (Sandbox Code Playgroud)

情节将只显示狗的信息,而不是鸟类或猫:

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)
Run Code Online (Sandbox Code Playgroud)

只显示狗,而不是猫或鸟:

Eso*_*ack 14

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

def figures_to_html(figs, filename="dashboard.html"):
    dashboard = open(filename, 'w')
    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])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 如果添加函数属性“fig.to_html(include_plotlyjs="cdn")”,文件大小将大大减小,但需要互联网连接才能加载。 (3认同)
  • 这解决了我遇到的一个问题。有没有办法启动/打开dashboard.html,而不是将其写入文件然后必须查找并打开它?类似于plotlyexpress在浏览器中自动打开的方式。有没有办法让图并排而不是堆叠? (2认同)
  • 为了减少最终 html 的大小,只需使用选项 `include_plotlyjs=True` 保存一个图形,使用 `include_plotlyjs=False` 保存其他图形就足够了。 (2认同)

jor*_*tos 7

您还可以使用袖扣尝试以下方法:

cf.subplots([df1.figure(kind='bar',categories='category'),
         df2.figure(kind='bar',categories='category')],shape=(2,1)).iplot()
Run Code Online (Sandbox Code Playgroud)

这应该给你:

  • @jorge santos - 在使用上面 - cufflinks.subplots([fig1],shape=(1,1)).iplot() 我收到以下错误: AttributeError: 'dict' object has no attribute 'iplot' 知道什么吗可能是替代方案或错误? (2认同)

bel*_*leb 6

您可以获得一个仪表板,其中包含几个图表,每个图表旁边都有图例:

import plotly
import plotly.offline as py
import plotly.graph_objs as go
fichier_html_graphs=open("DASHBOARD.html",'w')
fichier_html_graphs.write("<html><head></head><body>"+"\n")

i=0
while 1:
    if i<=40:
        i=i+1


        #______________________________--Plotly--______________________________________


        color1 = '#00bfff'
        color2 = '#ff4000'

        trace1 = go.Bar(
            x = ['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
            y = [25,100,20,7,38,170,200],
            name='Debit',
            marker=dict(
                color=color1
            )

        )
        trace2 = go.Scatter(

            x=['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
            y = [3,50,20,7,38,60,100],
            name='Taux',
            yaxis='y2'

        )
        data = [trace1, trace2]
        layout = go.Layout(
            title= ('Chart Number: '+str(i)),
            titlefont=dict(
            family='Courier New, monospace',
            size=15,
            color='#7f7f7f'
            ),
            paper_bgcolor='rgba(0,0,0,0)',
            plot_bgcolor='rgba(0,0,0,0)',

            yaxis=dict(
                title='Bandwidth Mbit/s',
                titlefont=dict(
                    color=color1
                ),
                tickfont=dict(
                    color=color1
                )
            ),
            yaxis2=dict(
                title='Ratio %',
                overlaying='y',
                side='right',
                titlefont=dict(
                    color=color2
                ),
                tickfont=dict(
                    color=color2
                )

            )

        )
        fig = go.Figure(data=data, layout=layout)
        plotly.offline.plot(fig, filename='Chart_'+str(i)+'.html',auto_open=False)
        fichier_html_graphs.write("  <object data=\""+'Chart_'+str(i)+'.html'+"\" width=\"650\" height=\"500\"></object>"+"\n")
    else:
        break


fichier_html_graphs.write("</body></html>")
print("CHECK YOUR DASHBOARD.html In the current directory")
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明


Nar*_*ali 5

新答案:

我们需要遍历每个动物并附加一个新的跟踪以生成您需要的内容。这将提供我希望的所需输出。

import pandas as pd
import numpy as np
import cufflinks as cf
import plotly.tools as tls
from plotly.offline import download_plotlyjs, plot,iplot
cf.go_offline()
import random

def generate_random_color():
    r = lambda: random.randint(0,255)
    return '#%02X%02X%02X' % (r(),r(),r())

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)

#shared Xaxis parameter can make this graph look even better
fig = tls.make_subplots(rows=2, cols=1)

for animal in ['dogs','cats','birds']: 
    animal_color = generate_random_color()
    fig1 = df1.iplot(kind='bar',barmode='stack',x='catagory',
                       y=animal,asFigure=True,showlegend=False, color = animal_color)
    fig.append_trace(fig1['data'][0], 1, 1)

    fig2 = df2.iplot(kind='bar',barmode='stack',x='catagory',
                       y=animal,asFigure=True, showlegend=False, color = animal_color)
    #if we do not use the below line there will be two legend
    fig2['data'][0]['showlegend'] = False

    fig.append_trace(fig2['data'][0], 2, 1)
    #additional bonus
    #use the below command to use the bar chart three mode
    # [stack, overlay, group]
    #as shown below
    #fig['layout']['barmode'] = 'overlay'
iplot(fig)
Run Code Online (Sandbox Code Playgroud)

输出: 堆积子图条形图

旧答案:

这将是解决方案

解释:

Plotly 工具有一个 subplot 函数来创建子图,您应该在这里阅读文档以获取更多详细信息。所以我首先使用袖扣来创建条形图的图形。需要注意的一件事是袖扣使用数据和布局创建和对象。Plotly 将只采用一个布局参数作为输入,因此我只采用袖扣图中的数据参数并将其 append_trace 附加到 make_suplots 对象。所以 fig.append_trace() 第二个参数是行号,第三个参数是列号

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

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

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
fig1 = df.iplot(kind='bar',barmode='stack',x='A',
                       y='B',asFigure=True)
fig.append_trace(fig1['data'][0], 1, 1)
df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('EFGH'))
fig2 = df2.iplot(kind='bar',barmode='stack',x='E',
                       y='F',asFigure=True)
fig.append_trace(fig2['data'][0], 2, 1)
iplot(fig)
Run Code Online (Sandbox Code Playgroud)

如果您想向子图添加通用布局,我建议您这样做

fig.append_trace(fig2['data'][0], 2, 1)
fig['layout']['showlegend'] = False
iplot(fig)
Run Code Online (Sandbox Code Playgroud)

甚至

fig.append_trace(fig2['data'][0], 2, 1)
fig['layout'].update(fig1['layout'])
iplot(fig)
Run Code Online (Sandbox Code Playgroud)

所以在绘图前的第一个示例中,我访问了布局对象的各个参数并对其进行了更改,您需要通过布局对象属性进行参考。

在绘图之前的第二个示例中,我使用袖扣生成的布局更新图形的布局,这将产生与我们在袖扣中看到的相同的输出。