【问题标题】:python: multiple barchart in subplotpython:子图中的多个条形图
【发布时间】:2021-09-22 18:46:39
【问题描述】:

为了绘制多个条形图,我使用以下代码:

import numpy as np 
import matplotlib.pyplot as plt 
 
X = ['Group A','Group B','Group C','Group D']
Ygirls = [10,20,20,40]
Zboys = [20,30,25,30]
  
X_axis = np.arange(len(X))
  
plt.bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls')
plt.bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys')
  
plt.xticks(X_axis, X)
plt.xlabel("Groups")
plt.ylabel("Number of Students")
plt.title("Number of Students in each group")
plt.legend()
plt.show()

得到这个结果:

我想使用相同的 y 轴绘制两个相互连接的图形。 对于普通条形图,代码为:

fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
fig.suptitle('Horizontally stacked subplots')
ax1.bar(, )
ax2.bar(, )
fig.subplots_adjust(wspace=0.0)
ax2.spines['left'].set_visible(False)
ax2.tick_params(axis='y', which='both', length=0)

如何修改多个条形图的代码?

【问题讨论】:

标签: python bar-chart subplot


【解决方案1】:

你想要的是一个堆积条形图:你可以查看这个示例代码here。 对于您的代码,它会是:

import numpy as np 
import matplotlib.pyplot as plt 

X = ['Group A','Group B','Group C','Group D']
Ygirls = [10,20,20,40]
Zboys = [20,30,25,30]
X_axis = np.arange(len(X))
fig, ax = plt.subplots()

ax.bar(X, Zboys, label = 'Boys')
ax.bar(X, Ygirls, label ='Grils', bottom=Zboys)
plt.xticks(X_axis, X)
plt.xlabel("Groups")
plt.ylabel("Number of Students")
plt.title("Number of Students in each group")
ax.legend()
plt.show()

输出会是这样的:

【讨论】:

  • 其实这不是我想要的。我想把两个数字并排贴在一起,而不是把条贴在一起
  • 那么,你不想要两个小节之间的间隙吗?
猜你喜欢
  • 2015-02-25
  • 2020-09-18
  • 2013-12-02
  • 2020-09-26
  • 2020-09-15
  • 1970-01-01
  • 2023-01-21
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多