Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

plotly库如何绘制数量不定的trace?

一、问题:从excel里读取数据,绘制气泡图。对于固定数量的trace,很容易绘制出图形(有几个trace,就手动设置几个trace的参数)。但是对于数量不固定的trace,该如何绘制出图形呢?
二、假定的excel数据:
image
三、我的半成品代码:

# 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']       # 请将数据放置在Sheet1表格左上角,以A1开始  
row_max = sheet.max_row  
col_max = sheet.max_column  
l=[]  
  
# size列表元素为z值(即葡萄各年的产量,跟气泡大小成正比  
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', 'US', '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, 1992, 1993, 1994, 1995, 1996, 1997],  
    y=['JAPAN', 'JAPAN', 'JAPAN', 'JAPAN', 'JAPAN', 'JAPAN', 'JAPAN'],  
    mode='markers+text',  
  
    marker=dict(  
        color='rgb(255, 130, 71)',  
        size=l[1],  
        showscale=False,  
    ),  
    text=list(map(str,l[1])),  
    textposition='middle center',  
)  
  
trace2 = go.Scatter(  
    x=[1991, 1992, 1993, 1994, 1995, 1996, 1997],  
    y=['CN', 'CN', 'CN', 'CN', 'CN', 'CN', 'CN'],  
    mode='markers+text',  
  
    marker=dict(  
        color='rgb(255, 193, 37)',  
        size=l[2],  
        showscale=False,  
    ),  
    text=list(map(str,l[2])),  
    textposition='middle center',  
)  
  
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)  
  
#启动绘图直接绘制figure对象  
# py.offline.init_notebook_mode()  
py.offline.plot(fig, filename='basic-scatter.html')

请高手指点,多谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...