Python绘制气泡图的源码

带图形界面的最新版本请见https://blog.csdn.net/wokaoyan1981/article/details/108563802)。

气泡图是一种特殊的散点图。每个气泡的大小与它代表的值成正比,横坐标通常代表年份,纵坐标通常代表分类。

利用Plotly库绘制出了一张漂亮的气泡图(代表1991年至1997年间中国、日本和美国每年的葡萄产量):

附上源代码:

import plotly as py
import plotly.graph_objs as go

# size列表元素为z值(即葡萄各年的产量,跟气泡大小成正比
size0 = [10, 14, 16, 18, 20, 42, 64]
size1 = [100, 30, 70, 85, 30, 42, 64]
size2 = [50, 22, 30, 65, 70, 66, 60]

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= size0,
        showscale = False,
        ),
    text=list(map(str, size0)),     #气泡上的数字标签,表示各年葡萄产量多少
    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=size1,
        showscale=False,
    ),
    text=list(map(str,size1)),
    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=size2,
        showscale=False,
    ),
    text=list(map(str,size2)),
    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')

猜你喜欢

转载自blog.csdn.net/wokaoyan1981/article/details/108459320