seaborn是专门用于统计数据可视化的包,可媲美R语言中的ggplot2包。本文介绍用seaborn绘制折线图。
环境
- python3.9
- win10 64bit
- seaborn==0.11.1
- matplotlib==3.3.4
- pandas==1.2.1
在seaborn中,绘制折线图的函数有lineplot
和relplot
。
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# 设置
pd.options.display.notebook_repr_html=False # 表格显示
plt.rcParams['figure.dpi'] = 75 # 图形分辨率
sns.set_theme(style='darkgrid') # 图形主题
单折线图
简单方式是传入pandas Series,其索引会成为x轴,值为y轴。
s=pd.Series([3,15,9,12,4],name='value')
sns.lineplot(data=s)
plt.show()

line_5_0.png
另一种方式是传入pandas dataFrame,通过设置x
,y
绘制。
df=pd.DataFrame(dict(x=range(5),y=[3,15,9,12,4]))
sns.lineplot(data=df,x='x',y='y')
plt.show()

line_7_0.png
置信区间折线图
当折线图中,x轴对应多个y轴数据时,seaborn会自动绘制置信区间。
# 加载数据
flights=pd.read_csv(r'https://gitee.com/nicedouble/seaborn-data/raw/master/flights.csv')
flights.head()
year month passengers
0 1949 January 112
1 1949 February 118
2 1949 March 132
3 1949 April 129
4 1949 May 121
# 含有置信区间的折线图
sns.lineplot(data=flights,x='year',y='passengers')
plt.show()

line_10_0.png
图中的阴影表示置信区间,默认是95%
,可以通过ci
参数修改置信区间。
# 显示置信区间为85%。
sns.lineplot(data=flights,x='year',y='passengers',ci=85)
plt.show()

line_12_0.png
多折线图
在一个图中绘制多条折线图。需要传入的数据为pandas dataFrame。
数据框为宽型数据或长型数据都可以绘制,这点要优于R语言的ggplot2。
当传入长型数据时,除了需要设置x
,y
参数外,还需要设置hue
或size
或style
参数。
- hue:颜色
- size:线宽
- style:样式
# 长型数据多折线图
sns.lineplot(data=flights,x='year',y='passengers',hue='month',style='month')
plt.show()

line_14_0.png
seaborn可以直接对宽型数据绘制多折线图,其索引成为x轴,所有的列自动绘制成多折线。
# 数据变成宽型数据
flights_wide = flights.pivot("year", "month", "passengers")
flights_wide.head()
month April August December February January July June March May
year
1949 129 148 118 118 112 148 135 132 121
1950 135 170 140 126 115 170 149 141 125
1951 163 199 166 150 145 199 178 178 172
1952 181 242 194 180 171 230 218 193 183
1953 235 272 201 196 196 264 243 236 229
month November October September
year
1949 104 119 136
1950 114 133 158
1951 146 162 184
1952 172 191 209
1953 180 211 237
# 宽型数据多折线图
sns.lineplot(data=flights_wide)
plt.show()

line_17_0.png
设置makers=True
参数可以显示散点。
# 增加散点
sns.lineplot(data=flights_wide,markers=True)
plt.show()

line_19_0.png
分面折线图
分面折线图的绘制,需要用relplot
函数。设置kind="line"
表示绘制折线图,设置col
或row
控制分面行为。
# 加载数据
fmri=pd.read_csv(r'https://gitee.com/nicedouble/seaborn-data/raw/master/fmri.csv')
fmri.head()
subject timepoint event region signal
0 s13 18 stim parietal -0.017552
1 s5 14 stim parietal -0.080883
2 s12 18 stim parietal -0.081033
3 s11 18 stim parietal -0.046134
4 s10 18 stim parietal -0.037970
# 按列分面折线图
sns.relplot(data=fmri, x="timepoint", y="signal",col="region", hue="event",
style="event",kind="line")
plt.show()

line_22_0.png
更多参考seaborn折线图