python - Matplotlib:我们可以在同一张图表上绘制直方图和箱形图吗?

标签 python matplotlib visualization histogram boxplot

我有一个关于绘制直方图和箱线图 Matplotlib 的问题。

我知道我可以分别绘制直方图和箱线图。我的问题是,是否可以将它们绘制在同一个图表上,例如本网站中显示的图表? Springer Images

非常感谢!

最佳答案

使用 matplotlib 有多种方法可以实现此目的。 plt.subplots() 方法以及 AxesGrid1gridspec 工具包都提供了非常优雅的解决方案,但可能需要时间来学习。

执行此操作的一种简单、强力的方法是自己手动将坐标区对象添加到图形中。

import numpy as np
import matplotlib.pyplot as plt

# fake data
x = np.random.lognormal(mean=2.25, sigma=0.75, size=37)

# setup the figure and axes
fig = plt.figure(figsize=(6,4))
bpAx = fig.add_axes([0.2, 0.7, 0.7, 0.2])   # left, bottom, width, height:
                                            # (adjust as necessary)
histAx = fig.add_axes([0.2, 0.2, 0.7, 0.5]) # left specs should match and
                                            # bottom + height on this line should
                                            # equal bottom on bpAx line
# plot stuff
bp = bpAx.boxplot(x, notch=True, vert=False)
h = histAx.hist(x, bins=7)

# confirm that the axes line up 
xlims = np.array([bpAx.get_xlim(), histAx.get_xlim()])
for ax in [bpAx, histAx]:
    ax.set_xlim([xlims.min(), xlims.max()])

bpAx.set_xticklabels([])  # clear out overlapping xlabels
bpAx.set_yticks([])  # don't need that 1 tick mark
plt.show()

关于python - Matplotlib:我们可以在同一张图表上绘制直方图和箱形图吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127635/

相关文章:

python - 如何在 Python 上使用 Selenium 选择日期范围?

python - 增加辅助 y 轴和 x 轴之间的间距?

python - 在 Python 中对系列进行分组

python - 改变 pyplot 图的 x 值的方向

javascript - Y 轴消失

python - 合并 Xarray 的 DataArray

python - 使用 Flask 和 MongoEngine 跟踪 Tumblelog 应用程序时出错

python - 乘以包含 NaN 的 Pandas 系列行

r - 在 R 包文档 (.Rd) 文件中包含图像

python - 具有不同轴范围的 Pandas 平行图