import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook_connected"Plotly-饼图+统计图+其他
1 饼图
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
# 这里导入了px自带的数据集,我们来看下数据长什么样
df.head()| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 23 | Albania | Europe | 2007 | 76.423 | 3600523 | 5937.029526 | ALB | 8 |
| 83 | Austria | Europe | 2007 | 79.829 | 8199783 | 36126.492700 | AUT | 40 |
| 119 | Belgium | Europe | 2007 | 79.441 | 10392226 | 33692.605080 | BEL | 56 |
| 155 | Bosnia and Herzegovina | Europe | 2007 | 74.852 | 4552198 | 7446.298803 | BIH | 70 |
| 191 | Bulgaria | Europe | 2007 | 73.005 | 7322858 | 10680.792820 | BGR | 100 |
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries' # 人口小于200w的国家,都叫others(???人少都不配出现在统计图里面了)
fig = px.pie(df, # 数据集的名字
values='pop', # 饼状图大小
names='country', # 饼状图label
title='Population of European continent' # 图名
)
fig.show()# help(px.pie)1.1 自动聚合
import plotly.express as px
# 导入小费数据
df = px.data.tips()
df.head()| total_bill | tip | sex | smoker | day | time | size | |
|---|---|---|---|---|---|---|---|
| 0 | 16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
| 1 | 10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
| 2 | 21.01 | 3.50 | Male | No | Sun | Dinner | 3 |
| 3 | 23.68 | 3.31 | Male | No | Sun | Dinner | 2 |
| 4 | 24.59 | 3.61 | Female | No | Sun | Dinner | 4 |
df.day.unique()array(['Sun', 'Sat', 'Thur', 'Fri'], dtype=object)
fig = px.pie(df, values='tip', names='day')
fig.show()1.2 配色
import plotly.express as px
df = px.data.tips()
fig = px.pie(df,
values='tip',
names='day',
color_discrete_sequence=px.colors.sequential.Redor_r # 关于可行的配色,上个项目已经介绍过了
)
fig.show()1.3 饼图加文字标注
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, # dataframe 名
values='pop', # 数值
names='country', # 类别
title='Population of American continent', # 标题
hover_data=['lifeExp'], # 鼠标浮动显示的数据
labels={'lifeExp':'life expectancy'} # 修改显示数据的名称
)
fig.update_layout(title_x=0.5)
fig.update_traces(textposition='inside', textinfo='percent+label',
)
# 在plotly中,图形格式的修改,是通过fig.update_traces()方法来实现的,这里我们调整文字的显示方式
fig.show()1.4 不显示看不见的字
有的字看不见,那我们干脆关掉他们的显示,这部分可以通过uniformtext_minsize 和 uniformtext_mode实现。
import plotly.express as px
df = px.data.gapminder().query("continent == 'Asia'")
fig = px.pie(df,
values='pop',
names='country')
fig.update_traces(textposition='inside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
# 设置最小字号为12号字,如果字号必须低于这个字号才能显示,则关闭该label的显示
fig.show()1.5 饼图挖洞 从pie变成Donut
import plotly.express as px
df = px.data.gapminder().query("continent == 'Asia'")
fig = px.pie(df,
values='pop',
hole = 0.5, # 在一半半径的位置挖洞
names='country')
fig.update_traces(textposition='inside')
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide')
# 设置最小字号为12号字,如果字号必须低于这个字号才能显示,则关闭该label的显示
fig.show()1.6 老前辈go绘制饼图
import plotly.graph_objects as go
labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500, 2500, 1053, 500]
fig = go.Figure(data=[go.Pie(labels=labels, values=values)])
fig.show()1.6.1 爆炸饼图
import plotly.graph_objects as go
labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500, 2500, 1053, 500]
fig = go.Figure(data=[go.Pie(labels=labels, values=values, pull=[0, 0, 0.1, 0.1])])
fig.show()1.7 旭日图
import plotly.express as px
df = px.data.tips()
fig = px.sunburst(df,
path=['day', 'time', 'sex'], # 三个级别(一半是离散数据)
values='total_bill' # 要展示的数据
)
fig.show()1.8 交互式表格
import plotly.graph_objects as go
import pandas as pd
import plotly.express as px
# 使用plotly.express内置的数据集tips,存储为DataFrame类型
df = px.data.tips() # 老朋友tips数据集
# 创建一个图形对象fig,用于绘制表格
fig = go.Figure(data=[go.Table(
header=dict(values=list(df.columns), # 提取数据框的列名作为表格的标题
fill_color='paleturquoise', # 设置标题栏的背景色为浅绿色
align='left'), # 指定标题文字的对齐方式为左对齐
cells=dict(values=[df.total_bill, df.tip, df.sex, df.smoker,df.day,df.time,df['size']], # 将数据框中的数据按列提取,填充到表格的单元格中
fill_color='lavender', # 设置单元格的背景色为淡紫色
align='left')) # 指定单元格文字的对齐方式为左对齐
])
# 显示图形
fig.show()1.8.1 修改表格尺寸
import plotly.graph_objects as go
# 定义表格数据,包括费用类别和对应的描述性文本
values = [['Salaries', 'Office', 'Merchandise', 'Legal', '<b>TOTAL<br>EXPENSES</b>'], #1st col
["Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad"]]
# 创建一个Figure对象,并添加一个Table trace
# 指定列的顺序和宽度
fig = go.Figure(data=[go.Table(
columnorder = [1,2],
columnwidth = [80,400], # 设定列宽
header = dict(
values = [['<b>EXPENSES</b><br>as of July 2017'],
['<b>DESCRIPTION</b>']],
line_color='darkslategray',
fill_color='royalblue',
align=['left','center'],
font=dict(color='white', size=12),
height=40 # 设定高度
),
cells=dict(
values=values,
line_color='darkslategray',
fill=dict(color=['paleturquoise', 'white']),
align=['left', 'center'],
font_size=12,
height=30)
)
])
# 显示图表
fig.show()1.9 矩形式树状结构图
import plotly.express as px
import numpy as np
# 加载 gapminder 数据集并筛选出 2007 年的数据
df = px.data.gapminder().query("year == 2007")
# 添加一个名为 "world" 的新列,值为 "world",以确保有一个单一的根节点
df["world"] = "world"
# 创建一个树状图可视化
# path 参数定义了树状图的层级结构,每一层应该是分类变量
# values 参数指定了用于聚合的列名
# color 参数指定了用于颜色编码的列名
# hover_data 参数添加了悬停时显示的额外信息
# color_continuous_scale 参数指定了连续数据的颜色渐变
# color_continuous_midpoint 参数根据人口加权计算生命期望的中点,作为颜色渐变的中间值
fig = px.treemap(df,
path=['world', 'continent', 'country'],
values='pop',
color='lifeExp',
hover_data=['iso_alpha'],
color_continuous_scale='RdBu',
color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop'])
)
# 显示树状图
fig.show()2 统计
2.1 箱线图
一种基于五位数摘要(“最小”,第一四分位数(Q1),中位数,第三四分位数(Q3)和“最大”)显示数据分布的标准化方法。
- 中位数(Q2 / 50th百分位数):数据集的中间值;
- 第一个四分位数(Q1 / 25百分位数):最小数(不是“最小值”)和数据集的中位数之间的中间数;
- 第三四分位数(Q3 / 75th Percentile):数据集的中位数和最大值之间的中间值(不是“最大值”);
- 四分位间距(IQR):第25至第75个百分点的距离;
- 离群值
- “最大”:Q3 + 1.5 * IQR
- “最低”:Q1 -1.5 * IQR
import plotly.express as px
df = px.data.tips() # 还是熟悉的小费数据
fig = px.box(df, y="total_bill")
#修改大小
fig.update_layout(width=400, height=400)
fig.show()2.1.1 通过引入x,提高绘图的维度
import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="time", y="total_bill")
fig.update_layout(width=400, height=400,
template="ggplot2")
fig.show()2.1.2 通过points把数据的显示打开(一定程度上弥补箱线图的缺陷)
import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="time", y="total_bill", points="all")
fig.update_traces(marker_color='rgb(158,202,225)', marker_line_color='rgb(8,48,107)',
marker_line_width=1.5, opacity=0.6)
fig.show()2.1.3 引入颜色维度
import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_layout(
title="Box Plot",
xaxis_title="Day",
yaxis_title="Total Bill",
legend_title="Smoker",
font=dict(
family="Courier New, monospace",
size=18,
color="RebeccaPurple"
)
)
fig.show()2.2 小提琴图
import plotly.express as px
from plotly.subplots import make_subplots
df = px.data.tips()
fig1 = px.violin(df, y="total_bill")
df = px.data.tips()
fig2 = px.violin(df, y="total_bill")
fig2.update_traces(box_visible=True, meanline_visible=True,meanline_color='Red')
fig = make_subplots(rows=1, cols=2, specs=[[{'type':'violin'}, {'type':'violin'}]])
# 将第一个小提琴图添加到第一个子图
for trace in fig1.data:
fig.add_trace(trace, row=1, col=1)
# 将第二个小提琴图添加到第二个子图
for trace in fig2.data:
fig.add_trace(trace, row=1, col=2)
# 更新布局以适应两个子图
fig.update_layout(title_text="Two Violin Plots Side by Side")
# 显示图表
fig.show()2.2.1 小提琴图、箱线图和散点图的结合
import plotly.express as px
df = px.data.tips()
fig = px.violin(df, y="total_bill", box=True, # draw box plot inside the violin
points='all', # can be 'outliers', or False
)
fig.show()2.2.2 颜色维度
import plotly.express as px
df = px.data.tips()
fig = px.violin(df, y="tip", x="smoker", color="sex", box=True, points="all",
hover_data=df.columns)
fig.show()2.2.3 分布对比
import plotly.express as px
# 加载内置的小费数据集
df = px.data.tips()
# 创建小提琴图
# 参数 y="tip" 表示 y 轴为 'tip' 列的数据,用于展示小费金额的分布情况
# 参数 color="sex" 表示根据 'sex' 列的不同值(性别)对小提琴图进行颜色区分
# 参数 violinmode='overlay' 表示将不同性别的小提琴图叠加显示,默认模式为 'group'
# 参数 hover_data=df.columns 表示当鼠标悬停在图表上时,显示所有列的数据信息
fig = px.violin(df, y="tip", color="sex",
violinmode='overlay',
hover_data=df.columns)
# 显示图表
fig.show()2.3 直方图
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill") # 指定需要绘制频率分布直方图的列名,若不指定聚合方法,默认为计数count
#修改大小
fig.update_layout(width=400, height=300)
fig.show()import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="day")
#修改大小
fig.update_layout(width=400, height=300)
fig.show()2.3.1 修改直方图直方个数
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill", nbins=200)
#修改大小
fig.update_layout(width=400, height=300)
fig.show()2.3.2 修改归一化方法
import plotly.express as px
df = px.data.tips()
# 创建一个直方图,用于展示'total_bill'(总账单)的分布情况
# histnorm参数设置为'probability density',使得y轴表示概率密度而不是频数
fig = px.histogram(df, x="total_bill", histnorm='probability density')
fig.update_layout(width=400, height=300)
fig.show()2.3.3 多个直方图
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill", color="sex")
fig.update_layout(width=400, height=300)
fig.show()2.3.4 二维分布
import plotly.express as px
df = px.data.tips()
fig = px.density_heatmap(df, x="total_bill", y="tip")
fig.update_layout(width=400, height=400)
fig.show()2.3.5 一维二维同时展示
import plotly.express as px
df = px.data.tips()
fig = px.density_heatmap(df,
x="total_bill",
y="tip",
marginal_x="histogram",
marginal_y="histogram"
)
fig.show()2.4 误差图
https://plotly.com/python/error-bars/
import plotly.express as px
df = px.data.iris()
df["e"] = df["sepal_width"]/100
fig = px.scatter(df,
x="sepal_width",
y="sepal_length",
color="species",
error_x="e",
error_y="e")
fig.show()# help(px.scatter)2.4.0.1 非对称方法展示
# 导入plotly.express模块,用于数据可视化
import plotly.express as px
# 加载iris数据集,这是一个常用的数据集,包含花卉的特征数据
df = px.data.iris()
# 新增e_plus列,用于表示正向误差条,这里简单地使用了sepal_width的百分之一作为示例
df["e_plus"] = df["sepal_width"]/100
# 新增e_minus列,用于表示负向误差条,这里简单地使用了sepal_width的百分之二点五作为示例
df["e_minus"] = df["sepal_width"]/40
# 使用scatter函数创建一个散点图,参数如下:
# x轴为sepal_width(花萼宽度),y轴为sepal_length(花萼长度),color根据species(物种)分色
# error_y和error_y_minus分别指定了正向和负向的误差条,以展示数据的可能波动范围
fig = px.scatter(df, x="sepal_width",
y="sepal_length",
color="species",
error_y="e_plus",
error_y_minus="e_minus")
# 显示图表
fig.show()2.4.0.2 线图加误差线
import plotly.graph_objects as go
# 创建一个图形对象
fig = go.Figure(data=go.Scatter(
# 设置散点图的x轴数据
x=[1, 2, 3, 4],
# 设置散点图的y轴数据
y=[2, 1, 3, 4],
# 配置y轴的误差条
error_y=dict(
# 指定误差条的数据类型
type='data',
# 设置误差条是否对称,此处设置为非对称
symmetric=False,
# 设置正向误差值
array=[0.1, 0.2, 0.1, 0.1],
# 设置反向误差值
arrayminus=[0.2, 0.4, 1, 0.2])
))
# 显示图形
fig.show()2.4.0.3 柱状图加误差线
import plotly.graph_objects as go
# 创建一个图形对象
fig = go.Figure()
# 向图形对象中添加一个条形图追踪,用于展示'Control'组的数据
fig.add_trace(go.Bar(
name='Control', # 设置条形图的名称
x=['Trial 1', 'Trial 2', 'Trial 3'], # 设置x轴标签
y=[3, 6, 4], # 设置y轴值
error_y=dict(type='data', array=[1, 0.5, 1.5]) # 设置y轴误差条的参数
))
# 向图形对象中添加另一个条形图追踪,用于展示'Experimental'组的数据
fig.add_trace(go.Bar(
name='Experimental', # 设置条形图的名称
x=['Trial 1', 'Trial 2', 'Trial 3'], # 设置x轴标签
y=[4, 7, 3], # 设置y轴值
error_y=dict(type='data', array=[0.5, 1, 2]) # 设置y轴误差条的参数
))
# 更新图形布局,设置条形图的显示模式为'group',以便对比不同组别的数据
fig.update_layout(barmode='group')
# 显示图形
fig.show()3 科技类图表
3.1 热力图
import plotly.graph_objects as go
fig = go.Figure(data=go.Heatmap(
z=[[1, 20, 30],
[20, 1, 60],
[30, 60, 1]]))
fig.update_layout(
width=300,
height=300
)
fig.show()3.1.1 自定义标签
import plotly.graph_objects as go
fig = go.Figure(data=go.Heatmap(
z=[[1, None, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]],
x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],# x轴解释标签
y=['Morning', 'Afternoon', 'Evening'], # y轴解释标签
)
)
fig.update_xaxes(side="top") # 把x轴标签移到图片上方
fig.show()3.1.2 以时间为横轴的heatmap展示
import plotly.graph_objects as go
import datetime
import numpy as np
np.random.seed(1) # 设定random seed,确保输出的一致性
programmers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne'] # 程序员们的名字
base = datetime.datetime.today()
dates = base - np.arange(180) * datetime.timedelta(days=1)
z = np.random.poisson(size=(len(programmers), len(dates))) # 随机生成一些活跃程度
fig = go.Figure(data=go.Heatmap(
z=z,
x=dates,
y=programmers,
colorscale='Viridis'))
fig.update_layout(
height = 400,
width = 1000,
title='GitHub commits per day',
xaxis_nticks=36)
fig.show()4 其他拓展
4.1 地理热图
import plotly.express as px
df = px.data.carshare() #导入官方的数据库
df.head()| centroid_lat | centroid_lon | car_hours | peak_hour | |
|---|---|---|---|---|
| 0 | 45.471549 | -73.588684 | 1772.750000 | 2 |
| 1 | 45.543865 | -73.562456 | 986.333333 | 23 |
| 2 | 45.487640 | -73.642767 | 354.750000 | 20 |
| 3 | 45.522870 | -73.595677 | 560.166667 | 23 |
| 4 | 45.453971 | -73.738946 | 2836.666667 | 19 |
fig = px.density_mapbox(df,
lat='centroid_lat', # 纬度
lon='centroid_lon', # 经度
z='car_hours', # 密度值
radius=10, # 高斯投影半径
)
# 配置底图参数
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon': sum(filter(None, df.centroid_lon))/len(list(filter(None, df.centroid_lon))),
'lat': sum(filter(None, df.centroid_lat))/len(list(filter(None, df.centroid_lat)))},
'zoom': 9
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()4.2 图表格式调整
4.2.1 图标标题、坐标标题、字体、图例
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
y=[0, 1, 2, 3, 4, 5, 6, 7, 8],
name="Name of Trace 1" # 图例1
))
fig.add_trace(go.Scatter(
x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
y=[1, 0, 3, 2, 5, 4, 7, 6, 8],
name="Name of Trace 2" # 图例1
))
fig.update_layout(
title="Plot Title", # 坐标标题
xaxis_title="x Axis Title", # 横轴标题
yaxis_title="y Axis Title", # 纵轴标题
# 字体设置
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
fig.show()import plotly.graph_objects as go
fig = go.Figure(go.Scatter(
y=[3, 1, 4],
x=["Mon", "Tue", "Wed"]))
# 更新标题,并制定标题位置
# 参数说明:
# title: 配置图表标题,包含以下子参数:
# - text: 标题文本内容
# - y: 标题垂直位置(基于图表区域高度归一化坐标,0-1之间)
# - x: 标题水平位置(基于图表区域宽度归一化坐标,0-1之间)
# - font: 配置标题字体样式,包含:
# * family: 字体族名称(支持多个备用字体)
# * size: 字体大小(单位:磅)
# * color: 字体颜色(十六进制格式)
fig.update_layout(
title={
'text': "Plot Title",
'y':0.9,
'x':0.5,
'font':dict(
family="Courier New, monospace",
size=28,
color="#7f7f7f")
}
)
fig.show()4.2.2 图表大小、页边距、背景
import plotly.express as px
df = px.data.tips()
fig = px.scatter(df,
x="total_bill",
y="tip",
facet_col="sex",
)
fig.update_layout(
width=800, # 修改绘图宽度
height=400, # 修改绘图高度
margin=dict(l=20, r=20, t=20, b=20), # 修改页边距
#paper_bgcolor="LightSteelBlue", # 修改页面背景
#浅绿色
paper_bgcolor=" rgb(200, 255, 200)",
)
fig.show()4.2.3 多图并列
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=1, cols=2) # 指定绘图的行数和列数
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[4, 5, 6],name = 'line1'),
row=1, col=1 # 绘制第1行第1列的图像
)
fig.add_trace(
go.Scatter(x=[20, 30, 40], y=[50, 60, 70],name = 'line2'),
row=1, col=2 # 绘制第1行第2列的图像
)
# 更新图片尺寸,标题
fig.update_layout(height=500, width=500, title_text="Side By Side Subplots",
title={'x':0.5})
fig.show()4.2.3.1 竖向合并
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=3, cols=1) # 三行一列
fig.append_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1) # 第1行第一列
fig.append_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1) # 第2行第一列
fig.append_trace(go.Scatter(
x=[0, 1, 2],
y=[10, 11, 12]
), row=3, col=1) # 第3行第一列
# 更新图片尺寸,标题
fig.update_layout(height=600, width=600, title_text="Stacked Subplots")
fig.show()4.2.3.2 网格状绘图
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=2, start_cell="bottom-left")
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
row=1, col=1)
fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
row=1, col=2)
fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
row=2, col=1)
fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
row=2, col=2)
fig.show()4.2.3.3 设定子图标题
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(
rows=2, cols=2,
subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
row=1, col=1)
fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
row=1, col=2)
fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
row=2, col=1)
fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
row=2, col=2)
fig.update_layout(height=500, width=500,
title_text="Multiple Subplots with Titles")
fig.show()4.2.3.4 自定义子图尺寸
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2, column_widths=[0.7, 0.3],
row_heights=[0.7])
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
row=1, col=1)
fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
row=1, col=2)
fig.show()4.2.3.5 多种类型的图形并列
Here are the possible values for the type option:
“xy”: 2D Cartesian subplot type for scatter, bar, etc. This is the default if no type is specified.
“scene”: 3D Cartesian subplot for scatter3d, cone, etc.
“polar”: Polar subplot for scatterpolar, barpolar, etc.
“ternary”: Ternary subplot for scatterternary.
“mapbox”: Mapbox subplot for scattermapbox.
“domain”: Subplot type for traces that are individually positioned. pie, parcoords, parcats, etc.
trace type: A trace type name (e.g. “bar”, “scattergeo”, “carpet”, “mesh”, etc.) which will be used to determine the appropriate subplot type for that trace.
以下是 type 选项的可能值:
"xy": 用于散点图、柱状图等的2D笛卡尔子图类型。如果未指定类型,这是默认值。"scene": 用于scatter3d、cone等的3D笛卡尔子图。"polar": 用于scatterpolar、barpolar等的极坐标子图。"ternary": 用于scatterternary的三元坐标子图。"mapbox": 用于scattermapbox的 Mapbox 子图。"domain": 用于单独定位的追踪类型的子图类型,例如pie、parcoords、parcats等。trace type: 追踪类型名称(例如"bar"、"scattergeo"、"carpet"、"mesh"等),将用于确定该追踪类型的适当子图类型。
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(
rows=2, cols=2,
specs=[[{"type": "xy"}, {"type": "polar"}],
[{"type": "domain"}, {"type": "scene"}]],
)
fig.add_trace(go.Bar(y=[2, 3, 1]),
row=1, col=1)
fig.add_trace(go.Barpolar(theta=[0, 45, 90], r=[2, 3, 1]),
row=1, col=2)
fig.add_trace(go.Pie(values=[2, 3, 1]),
row=2, col=1)
fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0],
z=[0.5, 1, 2], mode="lines"),
row=2, col=2)
fig.update_layout(height=700, showlegend=False)
fig.show()4.2.4 图片导出
Image export using the “kaleido” engine requires the kaleido package, which can be installed using pip:
$ pip install -U kaleido
import plotly.express as px
# 创建一个简单的饼图
df = px.data.tips()
fig = px.pie(df, values='tip', names='day')
# 将图表导出为 PNG 文件
fig.write_image("E:\杂项\新建文件夹\pie_chart.png")<>:8: SyntaxWarning:
invalid escape sequence '\p'
<>:8: SyntaxWarning:
invalid escape sequence '\p'
C:\Temp\ipykernel_3648\1356135783.py:8: SyntaxWarning:
invalid escape sequence '\p'
# 将图表导出为 JPEG 文件
fig.write_image("E:\杂项\新建文件夹\pie_chart.jpeg")<>:2: SyntaxWarning:
invalid escape sequence '\p'
<>:2: SyntaxWarning:
invalid escape sequence '\p'
C:\Temp\ipykernel_3648\2858125672.py:2: SyntaxWarning:
invalid escape sequence '\p'
# 将图表导出为 SVG 文件
fig.write_image("E:\杂项\新建文件夹\pie_chart.svg")<>:2: SyntaxWarning:
invalid escape sequence '\p'
<>:2: SyntaxWarning:
invalid escape sequence '\p'
C:\Temp\ipykernel_3648\2356755146.py:2: SyntaxWarning:
invalid escape sequence '\p'
# 将图表导出为 PDF 文件
fig.write_image("E:\杂项\新建文件夹\pie_chart.pdf")<>:2: SyntaxWarning:
invalid escape sequence '\p'
<>:2: SyntaxWarning:
invalid escape sequence '\p'
C:\Temp\ipykernel_3648\3764879754.py:2: SyntaxWarning:
invalid escape sequence '\p'