我对绘制直方图和箱形图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()

10-01 00:21