介绍
plotly是一个易于使用,功能强大的python绘图库,用于构建可交互式的图表(可以自行运行后使用鼠标拖拽图片试试),本系列文章将介绍plotly绘制各种类型图的方法,本文将介绍——水平条形图
水平条形图
基本水平条形图
代码解释
-
fig = go.Figure():这行代码创建了一个空的图表对象,fig是这个对象的变量名。Figure是Plotly中用于创建图表的类。
-
go.Bar(…):这是go模块中的Bar类的实例化,用于创建一个条形图。Bar类的参数定义了条形图的内容。
-
x=[20, 14, 23]:这是Bar类的一个参数,x代表条形图的数值部分,即每个条形的高度。在这个例子中,有三个数值:20、14和23。
-
y=[‘giraffes’, ‘orangutans’, ‘monkeys’]:这是Bar类的另一个参数,y代表条形图的类别标签,即每个条形所代表的对象。在这个例子中,有三个类别:长颈鹿(giraffes)、猩猩(orangutans)和猴子(monkeys)。
-
orientation=‘h’:这个参数设置条形图为水平方向。如果不设置这个参数或者设置为’v’,则条形图会是垂直方向的。
import plotly.graph_objects as go
fig = go.Figure(go.Bar(
x=[20, 14, 23],
y=['giraffes', 'orangutans', 'monkeys'],
orientation='h'))
fig.show()
带颜色的分类水平条形图
代码解释
-
fig.add_trace(go.Bar(…)): 这行代码用于向图表对象fig添加一个数据层(trace),每个go.Bar实例代表一组数据,即一个动物园的动物数量。
-
y和x参数分别定义了条形图的类别(动物名称)和数值(每种动物的数量),这是构成条形图基础的关键数据。
-
name参数用于为每个条形图轨迹命名,这样在图例中可以区分不同的数据集,便于识别图表中的各个部分。
-
orientation=‘h’: 这个参数设置条形图为水平方向,这是创建水平条形图的关键。
-
marker=dict(…): 这个字典定义了条形的颜色和边框样式,通过color和line来设置条形的外观,增强图表的视觉效果。
-
fig.update_layout(barmode=‘stack’): 通过update_layout方法和barmode='stack’参数,设置条形图的堆叠模式,使得不同动物园的数据在同一类别上堆叠起来,这样可以直观地比较不同类别的数量。
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(
y=['giraffes', 'orangutans', 'monkeys'],
x=[20, 14, 23],
name='SF Zoo',
orientation='h',
marker=dict(
color='rgba(246, 78, 139, 0.6)',
line=dict(color='rgba(246, 78, 139, 1.0)', width=3)
)
))
fig.add_trace(go.Bar(
y=['giraffes', 'orangutans', 'monkeys'],
x=[12, 18, 29],
name='LA Zoo',
orientation='h',
marker=dict(
color='rgba(58, 71, 80, 0.6)',
line=dict(color='rgba(58, 71, 80, 1.0)', width=3)
)
))
fig.update_layout(barmode='stack')
fig.show()
带折线图的条形图
代码解释
-
make_subplots: 创建一个包含两个子图的图表布局,rows=1, cols=2表示一行两列的子图布局。
-
fig.append_trace: 向图表中添加数据层,第一个参数是图表对象,第二个参数是子图的索引位置。这里分别添加了一个条形图(go.Bar)和一个散点图(go.Scatter)。
-
go.Bar: 表示居民储蓄数据,x=y_saving是储蓄占可支配收入的百分比,y=x是国家名称。marker参数定义了条形的颜色和边框样式。
-
go.Scatter: 表示居民净资产数据,x=y_net_worth是净资产(以百万美元/人均计算),y=x是国家名称。mode='lines+markers’表示使用线和标记点来展示数据。
-
fig.update_layout: 更新图表的布局和样式,包括标题、坐标轴设置、图例位置、边距和背景颜色等。
-
annotations: 创建一个注释列表,用于在图表上添加额外的文本信息,如具体的数值标签。
-
fig.show(): 显示最终的图表。
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
y_saving = [1.3586, 2.2623000000000002, 4.9821999999999997, 6.5096999999999996,
7.4812000000000003, 7.5133000000000001, 15.2148, 17.520499999999998
]
y_net_worth = [93453.919999999998, 81666.570000000007, 69889.619999999995,
78381.529999999999, 141395.29999999999, 92969.020000000004,
66090.179999999993, 122379.3]
x = ['Japan', 'United Kingdom', 'Canada', 'Netherlands',
'United States', 'Belgium', 'Sweden', 'Switzerland']
# Creating two subplots
fig = make_subplots(rows=1, cols=2, specs=[[{}, {}]], shared_xaxes=True,
shared_yaxes=False, vertical_spacing=0.001)
fig.append_trace(go.Bar(
x=y_saving,
y=x,
marker=dict(
color='rgba(50, 171, 96, 0.6)',
line=dict(
color='rgba(50, 171, 96, 1.0)',
width=1),
),
name='Household savings, percentage of household disposable income',
orientation='h',
), 1, 1)
fig.append_trace(go.Scatter(
x=y_net_worth, y=x,
mode='lines+markers',
line_color='rgb(128, 0, 128)',
name='Household net worth, Million USD/capita',
), 1, 2)
fig.update_layout(
title='Household savings & net worth for eight OECD countries',
yaxis=dict(
showgrid=False,
showline=False,
showticklabels=True,
domain=[0, 0.85],
),
yaxis2=dict(
showgrid=False,
showline=True,
showticklabels=False,
linecolor='rgba(102, 102, 102, 0.8)',
linewidth=2,
domain=[0, 0.85],
),
xaxis=dict(
zeroline=False,
showline=False,
showticklabels=True,
showgrid=True,
domain=[0, 0.42],
),
xaxis2=dict(
zeroline=False,
showline=False,
showticklabels=True,
showgrid=True,
domain=[0.47, 1],
side='top',
dtick=25000,
),
legend=dict(x=0.029, y=1.038, font_size=10),
margin=dict(l=100, r=20, t=70, b=70),
paper_bgcolor='rgb(248, 248, 255)',
plot_bgcolor='rgb(248, 248, 255)',
)
annotations = []
y_s = np.round(y_saving, decimals=2)
y_nw = np.rint(y_net_worth)
# Adding labels
for ydn, yd, xd in zip(y_nw, y_s, x):
# labeling the scatter savings
annotations.append(dict(xref='x2', yref='y2',
y=xd, x=ydn - 20000,
text='{:,}'.format(ydn) + 'M',
font=dict(family='Arial', size=12,
color='rgb(128, 0, 128)'),
showarrow=False))
# labeling the bar net worth
annotations.append(dict(xref='x1', yref='y1',
y=xd, x=yd + 3,
text=str(yd) + '%',
font=dict(family='Arial', size=12,
color='rgb(50, 171, 96)'),
showarrow=False))
# Source
annotations.append(dict(xref='paper', yref='paper',
x=-0.2, y=-0.109,
text='OECD "' +
'(2015), Household savings (indicator), ' +
'Household net worth (indicator). doi: ' +
'10.1787/cfc6f499-en (Accessed on 05 June 2015)',
font=dict(family='Arial', size=10, color='rgb(150,150,150)'),
showarrow=False))
fig.update_layout(annotations=annotations)
fig.show()