matplotlib中的多级直方图
亲爱的python/matplotlib社区,
我在使用matplotlib的时候遇到了一些问题:我似乎无法在同一个图表空间中绘制多个重叠的直方图,使用的代码是:
binsize = 0.05
min_x_data_sey, max_x_data_sey = np.min(logOII_OIII_sey), np.max(logOII_OIII_sey)
num_x_bins_sey = np.floor((max_x_data_sey - min_x_data_sey) / binsize)
min_x_data_comp, max_x_data_comp = np.min(logOII_OIII_comp), np.max(logOII_OIII_comp)
num_x_bins_comp = np.floor((max_x_data_comp - min_x_data_comp) / binsize)
min_x_data_sf, max_x_data_sf = np.min(logOII_OIII_sf), np.max(logOII_OIII_sf)
num_x_bins_sf = np.floor((max_x_data_sf - min_x_data_sf) / binsize)
axScatter_farright = fig.add_subplot(gs_right[0,0])
axScatter_farright.tick_params(axis='both', which='major', labelsize=10)
axScatter_farright.tick_params(axis='both', which='minor', labelsize=10)
axScatter_farright.set_ylabel(r'$\mathrm{N}$', fontsize='medium')
axScatter_farright.set_xlim(-1.5, 1.0)
axScatter_farright.set_xlabel(r'$\mathrm{log([OII]/[OIII])}$', fontsize='medium')
axScatter_farright.hist(logOII_OIII_sey, num_x_bins_sey, ec='0.3', fc='none', histtype='step')
axScatter_farright.hist(logOII_OIII_comp, num_x_bins_comp, ec='0.3', fc='none', histtype='step')
axScatter_farright.hist(logOII_OIII_sf, num_x_bins_sf, ec='0.3', fc='none', histtype='step')
看起来坐标轴类无法处理多个直方图?如果我哪里错了,请纠正我。
我的整体图表是1行3列的布局。我想用网格规格来让图表看起来更好。
到目前为止,我的图表看起来是这样的:
我希望图表中的直方图部分看起来像这样,包含步骤类型的直方图重叠(带图例):
我有三个不同的元组类型数组,这些数据是从一个csv文件生成的。也就是说,使用 x, y = np.genfromtext(datafile.csv)
如果有人能解释一下怎么做到这一点,我将非常感激。
1 个回答
3
你现在做的应该是没问题的。有没有可能你设置的范围(-1.5到1)里,只有一个分布在这个范围内呢?(也就是说,试着去掉手动设置的 set_xlim
语句,看看其他的分布是否会出现。)
这里有一个简单的例子,可以证明这个操作应该是有效的:
import numpy as np
import matplotlib.pyplot as plt
num = 1000
d1 = np.random.normal(-1, 1, num)
d2 = np.random.normal(1, 1, num)
d3 = np.random.normal(0, 3, num)
fig, ax = plt.subplots()
ax.hist(d1, 50, ec='red', fc='none', lw=1.5, histtype='step', label='Dist A')
ax.hist(d2, 50, ec='green', fc='none', lw=1.5, histtype='step', label='Dist B')
ax.hist(d3, 100, ec='blue', fc='none', lw=1.5, histtype='step', label='Dist C')
ax.legend(loc='upper left')
plt.show()
(如果你想让图例显示线条而不是方框,你需要使用一个代理艺术家。如果你需要,我可以加个例子。不过这不在这个问题的范围内。)