2017-08-08 637 views
2

這些資源顯示如何從單個Pandas DataFrame中獲取數據並在Plotly圖上繪製不同列的子圖。我有興趣從獨立的DataFrame創建圖形,並將它們繪製爲與子圖相同的圖形。 Plotly可能嗎?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) 

編輯: 這是基於那仁的反饋的例子:

創建數據框:

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:

回答

2

你可以得到一個包含多個圖表與傳說儀表板每一個旁:

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") 

結果:

enter image description here

+1

這正是我所期待的。非常感謝!!! – sparrow

3

新建答案:

我們通過每一個需要循環動物和追加一個新的軌跡來產生你需要的東西。這將給我期望的輸出。

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) 

輸出: stacked subplot bar chart

老答案:

這將是解決

說明:

Plotly工具有一個插曲函數來創建插曲您應該閱讀文檔以獲取更多詳細信息here。所以我首先使用袖釦來創建條形圖。有一點需要注意的是袖釦的創建和對象的數據和佈局。 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) 

如果你想添加一個共同佈局,次要情節,我建議你做

fig.append_trace(fig2['data'][0], 2, 1) 
fig['layout']['showlegend'] = False 
iplot(fig) 

甚至

fig.append_trace(fig2['data'][0], 2, 1) 
fig['layout'].update(fig1['layout']) 
iplot(fig) 

所以在繪製之前,第一個例子,我訪問佈局對象的各個參數,並改變它們,你需要去通過佈局對象屬性refernce。

在繪圖之前的第二個示例中,我使用袖釦生成的佈局更新了圖形的佈局,這將產生與我們在袖釦中看到的輸出相同的輸出。

+0

感謝@Naren,我試過,但它只是顯示一些在這兩個次要情節的數據。我已經添加了一個例子來說明我的問題正在發生什麼。 – sparrow

+1

@sparrow基於您的新更新更新我的答案。 –

+0

非常感謝你的幫助@Naren! – sparrow

2

您也可以嘗試以下方法使用袖釦:

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

這應該給你:

+0

Thanks @jorge!使它變得容易。 – sparrow

+0

我注意到,當我用堆積的條形圖將此刪除時,「堆疊」質量被刪除。有沒有一種方法可以將數字插入到子圖中而不會刪除它們的任何屬性?我試過這個:iplot(cf.subplots([fig1,fig2],shape =(2,1))) – sparrow