一、問題:從excel里讀取資料,繪制氣泡圖。對于固定數量的trace,很容易繪制出圖形(有幾個trace,就手動設定幾個trace的引數)。但是對于數量不固定的trace,該如何繪制出圖形呢?
二、假定的excel資料:

三、我的半成品代碼:
# 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=https://bbs.csdn.net/topics/data, layout=layout)
#啟動繪圖直接繪制figure物件
# py.offline.init_notebook_mode()
py.offline.plot(fig, filename='basic-scatter.html')
請高手指點,多謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/7039.html
