Python-“万水千山图”
山峦图,也称为堆叠密度图(Ridgeline Plot),展示多个分布的密度曲线,通常以重叠或有间距的形式排列。这种图形类似于山峦的轮廓,因而得名。它通过使用核密度估计(KDE)或直方图来表示各组数据的分布特征,并在纵轴上将各分布分组排列。
matplotlib结合seaborn中的FacetGrid/kdeplot结合可以很好的实现山峦图,还是使用“weather数据集”。
# 21.2_01
# -*- encoding: utf-8 -*-
'''
未经过允许禁止转载!
@Author : 公众号: pythonic生物人
@Desc : seaborn山峦图
'''import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 数据准备
months = weather.index.month_name().unique() # 获取数据索引中的唯一月份名称
data = []
for month in months:
low_temps = weather[weather.index.month_name() == month]["最低温度(F)"]
data.append(
pd.DataFrame({
"Month": [month] * len(low_temps),
"Temperature": low_temps
}))
df = pd.concat(data, ignore_index=True)
# 绘图
g = sns.FacetGrid(
df,
row="Month",
hue="Month",
aspect=10,
height=0.5,
palette=sns.color_palette(palette='autumn', n_colors=12),
) # FacetGrid细节参考教程章节“12.2 axes-level结合FacetGrid分面图(19种)”
g.map(
sns.kdeplot,
"Temperature",
bw_adjust=1,
clip_on=False,
fill=True,
alpha=1,
linewidth=1.0,
)
g.map(
sns.kdeplot,
"Temperature",
clip_on=False,
color="w",
lw=2,
bw_adjust=1,
)
g.refline(y=0, linewidth=0.4, linestyle="-", color="black",
clip_on=False) # 添加参考线
def label(x, color, label):
ax = plt.gca()
ax.text(0,
0.2,
label,
fontsize=10,
color="black",
ha="left",
va="center",
transform=ax.transAxes)
g.map(label, "Temperature") # 添加左侧月份标签
g.set_axis_labels("温度($\degree$F)", "", fontsize=12) #x轴标题
g.figure.suptitle("月温度($\degree$F)变化山脊图", fontsize=14, x=0.3, y=0.92) #figure标题
g.figure.subplots_adjust(hspace=-0.65) # 设置子图之间的间距为负值,实现重叠效果
g.set_titles("") #关闭子图的标题
g.set(
yticks=[], #移除子图y轴上的刻度标记
ylabel="") #移除子图y轴的标题
g.despine(
bottom=True, #移除子图x轴的底部边框
left=True #移除子图y轴的左边框
)
g.fig.set_dpi(200) # 设置分辨率
g.figure.patch.set_edgecolor('gray') # 设置外框颜色为灰色
g.figure.patch.set_linewidth(0.6) # 设置外框线宽
plt.show()
更详细代码即将添加到教程中: 👉《Python可视化教程》,优惠中!