python - 如何在python中创建分组条形图的子图
问题描述
我想将多个分组的条形图组合成一个图形,如下图所示。 在单个图中分组条形图
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]
首先,我创建了每个分组条形图plt.subplots()
x = np.arange(len(labels))
width = 0.3
fig1, ax = plt.subplots()
rects1 = ax.bar(x-width/2, yesterday_test1_mean, width)
rects2 = ax.bar(x+width/2, yesterday_test2_mean, width)
fig2, ax = plt.subplots()
rects3 = ax.bar(x-width/2, today_test1_mean, width)
rects4 = ax.bar(x+width/2, today_test2_mean, width)
然后,我add_subplot
试图将fig1
和fig2
用作新图形中的新轴。
fig_all = plt.figure()
fig1 = fig_all.add_subplot(1,2,1)
fig2 = fig_all.add_subplot(1,2,2)
fig_all.tight_layout()
plt.show()
但它没有用。如何将多个分组条形图组合成一个图形?
提前致谢。
解决方案
好吧,我尝试了一些东西。这是一个粗略的结果。我唯一改变的是,我只是使用随着时间的推移而学习的子图,而不是使用轴。所以以 fig 和 axes 作为输出,也一定有办法。但这就是我用过的全部。我还没有添加图例和标题,但我想你也可以自己尝试一下。
这是代码,只需稍作改动:
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]
x = np.arange(len(labels))
width = 0.3
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.bar(x-width/2, yesterday_test1_mean, width)
plt.bar(x+width/2, yesterday_test2_mean, width)
plt.subplot(122)
plt.bar(x-width/2, today_test1_mean, width)
plt.bar(x+width/2, today_test2_mean, width)
plt.show()
当您看到结果并自己尝试一些东西时,让我尝试添加标签和图例,以及您在示例图像中提供的内容。
编辑:最终输出
所以这就是你要找的东西:
代码: import matplotlib.pyplot as plt import numpy as np
labels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]
x = np.arange(len(labels))
width = 0.3
plt.figure(figsize=(12,5))
plt.subplot(121)
plt.title('Yesterday', fontsize=18)
plt.bar(x-width/2, yesterday_test1_mean, width, label='test1', hatch='//', color=np.array((199, 66, 92))/255)
plt.bar(x+width/2, yesterday_test2_mean, width, label='test2', color=np.array((240, 140, 58))/255)
plt.xticks([0,1,2], labels, fontsize=15)
plt.subplot(122)
plt.title('Today', fontsize=18)
plt.bar(x-width/2, today_test1_mean, width, hatch='//', color=np.array((199, 66, 92))/255)
plt.bar(x+width/2, today_test2_mean, width, color=np.array((240, 140, 58))/255)
plt.xticks([0,1,2], labels, fontsize=15)
plt.figlegend(loc='upper right', ncol=1, labelspacing=0.5, fontsize=14, bbox_to_anchor=(1.11, 0.9))
plt.tight_layout(w_pad=6)
plt.show()
推荐阅读
- regex - 使用 beautifulsoup 去除 HTML 中的脚本文本
- java - OneToMany 与同一类的另一个实例的关系
- c++ - nullptr 是假的吗?
- r - 从 NetCDF 以 OPeNDAP DODs(分布式海洋数据系统)格式创建栅格图层
- ansible - 如何将变量添加到前缀路径?
- angular - 如何隔离 Angular / Typescript 中的私有静态函数?
- angular - 在 Angular 应用程序中启用完整的模板类型检查
- vba - VBA 和 Bloomberg 应用程序。运行“RefreshAllWorkbooks”
- karate - 如何在空手道 API 断言语句中放置“或”运算符
- python - QMetaProperty::read: 无法处理未注册的数据类型 'QAbstractListModel*'