我想将多个分组条形图合并合并到一个图中,如下图所示。grouped bar charts in a single figure
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()
型
但是它不起作用。我怎么能把几个分组的条形图合并成一个图形呢?
先谢了。
2条答案
按热度按时间vaj7vani1#
好吧,我尝试了一些东西。这是一个粗略的结果。我唯一改变的是,而不是使用轴,我只是使用子图,因为我学到了很多。所以与
fig
和axes
作为输出,一定有一种方法。但这是我曾经使用过的。我还没有添加图例和标题,但我想你也可以自己尝试。下面是代码,只有很小的变化:
字符串
这是初始结果:
当您看到结果并自己尝试一些东西时,让我尝试添加标签和图例,以及您在示例图像中提供的内容。
编辑:最终输出
这就是你要找的东西
的
代码:import matplotlib.pyplot as plt import numpy as np
型
kyxcudwk2#
有两种方法来做子图,你可能会尝试合并意外:
plt.subplot
和plt.subplots
。下面是如何使用
plt.subplots
创建两个条形图的示例。字符串
您的代码只有很小的变化。您可以使用以下命令添加标签:
型