python plotly:未固定的跟踪数

问题描述

我的代码从.xlsx文件读取数据,并通过使用plotly绘制Bubble图。 Bubble Diagram 当我确实知道需要绘制多少条迹线时,此任务很容易。但是,由于行数是可变的,所以当跟踪数不固定时,我陷入了困惑。


       1991  1992  1993  1994  1995  1996  1997
US       10    14    16    18    20    42    64
JAPAN   100    30    70    85    30    42    64
CN       50    22    30    65    70    66    60

这是我未完成的代码

# Version 2 Could read data from .xlsx file.
import plotly as py
import plotly.graph_objs as go
import openpyxl

wb = openpyxl.load_workbook(('grape output.xlsx'))     
sheet = wb['Sheet1']       
row_max = sheet.max_row
col_max = sheet.max_column
l=[]

for row_n in range(row_max-1):
    l.append([])
    for col_n in range(col_max-1):
        l[row_n].append(sheet.cell(row=row_n+2,column=col_n+2).value)

trace0 = go.Scatter(
    x=[1991,1992,1993,1994,1995,1996,1997],y=['US','US','US'],mode='markers+text',marker=dict(
        color='rgb(150,204,90)',size= l[0],showscale = False,),text=list(map(str,l[0])),textposition='middle center',)

trace1 = go.Scatter(
    x=[1991,y=['JAPAN','JAPAN','JAPAN'],marker=dict(
        color='rgb(255,130,71)',size=l[1],showscale=False,l[1])),)

trace2 = go.Scatter(
    x=[1991,y=['CN','CN','CN'],193,37)',size=l[2],l[2])),)

layout = go.Layout(plot_bgcolor='rgb(10,10,10)',paper_bgcolor='rgb(20,55,100)',font={               
                       'size': 15,'family': 'sans-serif','color': 'rgb(255,255,255)'  
                   },width=1000,height=500,xaxis=dict(title='Output of grapes per year in US,JAPAN and CN',showlegend=False,margin=dict(l=100,r=100,t=100,b=100),hovermode = False,)

data = [trace0,trace1,trace2]
fig = go.figure(data=data,layout=layout)


py.offline.init_notebook_mode()
py.offline.plot(fig,filename='basic-scatter.html')

您能教我如何画它们吗?谢谢

解决方法

Derek O.的答案很完美,但我认为有一种使用plotly.express的灵活方法,尤其是在您不想定义颜色的情况下。

想法是正确地转换数据。

数据

import pandas as pd
df = pd.DataFrame({1991:[10,100,50],1992:[14,30,22],1993:[16,70,30],1994:[18,85,65],1995:[20,70],1996:[42,42,66],1997:[64,64,60]})
df.index = ['US','JAPAN','CN']
df = df.T.unstack()\
      .reset_index()\
      .rename(columns={"level_0": "country","level_1": "year",0: "n"})
print(df)
   country  year    n
0       US  1991   10
1       US  1992   14
2       US  1993   16
3       US  1994   18
4       US  1995   20
5       US  1996   42
6       US  1997   64
7    JAPAN  1991  100
8    JAPAN  1992   30
9    JAPAN  1993   70
10   JAPAN  1994   85
11   JAPAN  1995   30
12   JAPAN  1996   42
13   JAPAN  1997   64
14      CN  1991   50
15      CN  1992   22
16      CN  1993   30
17      CN  1994   65
18      CN  1995   70
19      CN  1996   66
20      CN  1997   60

使用plotly.express

现在您的数据采用长格式,您可以按以下方式使用plotly.express

import plotly.express as px
fig = px.scatter(df,x="year",y="country",size="n",color="country",text="n",size_max=50 # you need this otherwise the bubble are too small
                )

fig.update_layout(plot_bgcolor='rgb(10,10,10)',paper_bgcolor='rgb(20,55,100)',font={'size': 15,'family': 'sans-serif','color': 'rgb(255,255,255)'
                       },width=1000,height=500,xaxis=dict(title='Output of grapes per year in selected countries',),showlegend=False,margin=dict(l=100,r=100,t=100,b=100),hovermode = False,)
# Uncomment this if you don't wont country as yaxis title
# fig.layout.yaxis.title.text = None
fig.show()

enter image description here

,

我应该指出,如果您将原始数据附加为文本或可以更轻松地复制和粘贴的内容,则代码的重现性更高。但是,无论如何,我仍然可以回答您的问题并为您指明正确的方向。

您应该做的是使用循环,然后从查看data = [trace0,trace1,trace2]行开始。如您所见,如果您有100个国家(而不是3个),则此方法将无法扩展。

相反,您可以使用列表理解功能将data创建为列表,并更新每个跟踪的变化部分。 trace0trace1trace2除了国家/地区,值和颜色没有太大区别。为了显示您的意思,我使用DataFrame重新创建了您的数据,然后创建了包含您的国家和颜色的单个列表。

# Version 2 could read data from .xlsx file.
import plotly as py
import plotly.graph_objs as go
import openpyxl

# wb = openpyxl.load_workbook(('grape output.xlsx'))     
# sheet = wb['Sheet1']       
# row_max = sheet.max_row
# col_max = sheet.max_column
# l=[]

# for row_n in range(row_max-1):
#     l.append([])
#     for col_n in range(col_max-1):
#         l[row_n].append(sheet.cell(row=row_n+2,column=col_n+2).value)

import pandas as pd

df = pd.DataFrame({1991:[10,'CN']
colors = ['rgb(150,204,90)','rgb(255,130,71)',193,37)']

data = [go.Scatter(
    x=df.columns,y=[country]*len(df.columns),mode='markers+text',marker=dict(
        color=colors[num],size= df.loc[country],showscale = False,text=list(map(str,df.loc[country])),textposition='middle center',)
    for num,country in enumerate(df.index)
]

layout = go.Layout(plot_bgcolor='rgb(10,font={               
                       'size': 15,255)'  
                   },xaxis=dict(title='Output of grapes per year in US,JAPAN and CN',)

# data = [trace0,trace2]
fig = go.Figure(data=data,layout=layout)
fig.show()

# py.offline.init_notebook_mode()
# py.offline.plot(fig,filename='basic-scatter.html')

enter image description here

如果我随后将带有1991-1997值的测试国家/地区添加到数据框,则无需更改其余代码,气泡图也会相应更新。

# I added a test country with data
df = pd.DataFrame({1991:[10,50,10],22,20],65,40],66,60],60,70]})
df.index = ['US','CN','TEST']
colors = ['rgb(150,37)','rgb(100,100)']

enter image description here

,

代码已更新至第2版,可以从.xlsx文件读取数据并绘制气泡图。 与上一个项目相比,名为“ grape output.xlsx”的原始数据已添加了新项目:

             1991  1992  1993  1994  1995  1996  1997  1998  1999
         US    10    14    16    18    20    42    64   100    50
      JAPAN   100    30    70    85    30    42    64    98    24
         CN    50    22    30    65    70    66    60    45    45
      INDIA    90    88    35    50    90    60    40    66    76
         UK    40    50    70    50    25    30    22    40    60

代码如下:

# Version 2 
import plotly as py
import plotly.graph_objs as go
import openpyxl
import pandas as pd


wb = openpyxl.load_workbook('grape output.xlsx')
sheet = wb['Sheet1']
row_max = sheet.max_row
col_max = sheet.max_column
first_row_list = []
first_col_list = []
for col_n in range(2,col_max+1):
    first_row_list.append(sheet.cell(row=1,column=col_n).value)
for row_n in range(2,row_max+1):
    first_col_list.append(sheet.cell(row=row_n,column=1).value)

data_all = pd.read_excel('grape output.xlsx')
data = data_all.loc[:,first_row_list]

df = pd.DataFrame(data)
df.index = first_col_list
colors = ['rgb(150,'rgb(180,240,190)',1)','rgb(25,19,3)','rgb(45,24,200)','rgb(33,58,108)','rgb(35,208,232)']

data = [go.Scatter(
    x=df.columns,country in enumerate(reversed(df.index))
]

layout = go.Layout(plot_bgcolor='rgb(10,font={
                       'size': 15,255)'
                   },height=800,JAPAN and CN'),)

fig = go.Figure(data=data,layout=layout)
py.offline.plot(fig,filename='basic-scatter.html')

现在的结果是这样的: updated bubble diagram 仍然存在一些小问题:

  1. 如何摆脱1990和2000这两个数字以及1990和2000的白色垂直线?
  2. 如何绘制1991、1993、1995、1997、1999的白线并将这些年显示为横坐标轴?

请更正代码Versinon 2以对其进行改进。谢谢!