python - 在python中叠加两个单独的直方图
问题描述
我有两个单独的数据框,我将它们制作成直方图,我想知道如何覆盖它们,因此对于 x 轴上的每个类别,条形图对于每个数据框都是不同的颜色。这是我用于单独条形图的代码。
df1.plot.bar(x='brand', y='desc')
df2.groupby(['brand']).count()['desc'].plot(kind='bar')
我试过这段代码:
previous = df1.plot.bar(x='brand', y='desc')
current= df2.groupby(['brand']).count()['desc'].plot(kind='bar')
bins = np.linspace(1, 4)
plt.hist(x, bins, alpha=0.9,normed=1, label='Previous')
plt.hist(y, bins, alpha=0.5, normed=0,label='Current')
plt.legend(loc='upper right')
plt.show()
此代码未正确覆盖图形。问题是数据框 2 没有数值,所以我需要使用 count 方法。感谢帮助!
解决方案
您可能必须在 matplotlib 中使用轴对象。简单来说,您创建一个图形,其中包含一些与之关联的轴对象,然后您可以从中调用 hist。这是您可以做到的一种方法:
fig, ax = plt.subplots(1, 1)
ax.hist(x, bins, alpha=0.9,normed=1, label='Previous')
ax.hist(y, bins, alpha=0.5, normed=0,label='Current')
ax.legend(loc='upper right')
plt.show()
推荐阅读
- android - 在 Android 意图中传递模拟类
- php - 将 b64 图片支持添加到 HTML Purifier 的默认白名单中
- java - 是否可以强制 Eclipse 为已编译的 java 类保留准确的行号?
- vba - 比较vba中的日期
- angular - 如何在 nx 库中使用 APP_INITIALIZER?
- raspberry-pi - LoRa 点对点限制
- azure - 使用 Batch-Shipyard 在虚拟网络中配置 Azure Batch 池
- vba - 如果工作簿已打开,则继续
- laravel - 如何在锚标记数据值中设置图像 url
- ios - iOS中的压缩PNG文件错误组