如何绘制两个非堆叠并列显示的直方图,避免相互重叠
实现双直方图并列展示的方案
你原有代码将两个直方图都绘制在同一张画布的默认坐标系上,所以会出现重叠。只需通过plt.subplots()创建1行2列的独立子图,分别将两个直方图绑定到不同子图坐标系即可实现并列展示。
修改后的完整代码如下:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 导入数据 members = pd.read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-22/members.csv") sns.set(palette="Reds_r") # 创建1行2列的子图布局,可调整nrows、ncols改为上下排列或其他布局 fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(15, 10)) members_injury_height = members["injury_height_metres"] members_death_height = members["death_height_metres"] # 第一个子图绘制受伤高度分布 members_injury_height.hist(ax=ax1, density=True, alpha=0.5, bins=20) ax1.set_xlabel("高度(米)") ax1.set_ylabel("受伤成员占比") ax1.set_title("成员受伤高度分布") ax1.set_facecolor('whitesmoke') ax1.legend(['受伤']) # 第二个子图绘制死亡高度分布 members_death_height.hist(ax=ax2, density=True, alpha=0.2, bins=20) ax2.set_xlabel("高度(米)") ax2.set_ylabel("死亡成员占比") ax2.set_title("成员死亡高度分布") ax2.set_facecolor('whitesmoke') ax2.legend(['死亡']) # 自动调整子图间距,避免标签、标题重叠 plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者easy
相关产品推荐
相关产品推荐

