python - 如何使用 matplotlib(无 Pandas )并排绘制两个图

标签 python matplotlib jupyter-notebook data-science

我完全不在自己的舒适区,但有人要求我并排绘制一些数据。我设法将我的数据绘制成图表,但我不知道如何让它们并排绘制。我已经阅读了有关使用 plt.subplot 的信息,但我无法成功使用它(它只给我空白图表)。这是我的两个图表的代码:


def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


plt.rcParams['figure.figsize']=(7,6)
labels = monthNames

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, financeMonthlyDefects, width, label='Defects', color = 'r')
rects2 = ax.bar(x + width/2, financeMonthlyDeployments, width, label='Deployments',)

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_title('Finance Systems Deployments/Defects')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
ax.set_xlabel('Iteration Month & Year')
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

autolabel(rects1)
autolabel(rects2)

### BEGIN GLOBAL FINANCE ###
plt.rcParams['figure.figsize']=(7,6)
labels = monthNames

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, globalFinancingMonthlyDefects, width, label='Defects', color = 'r')
rects2 = ax.bar(x + width/2, globalFinancingMonthlyDeployments, width, label='Deployments',)

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_title('Global Finance Deployments/Defects')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
ax.set_xlabel('Iteration Month & Year')
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

autolabel(rects1)
autolabel(rects2)

现在是这样输出的:Vertically stacked :(

最佳答案

每次调用 subplots() 时,都会创建一个新图形,这不是您想要的。要获得并排图,请执行 fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) 然后使用 ax1在左侧绘图上绘制您想要的任何内容,在右侧绘图上绘制 ax2

关于python - 如何使用 matplotlib(无 Pandas )并排绘制两个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57279892/

相关文章:

python - pytest.raises(Error) 如何工作?

python - 在python中索引所有*除了*一项

python - Pandas 数据帧 : Replace charactere conditionally

python - 机器人框架和 Django

python - 通过垂直拆分文本文件创建列表

python - 在 matplotlib 等高线图中选择颜色

python - 将 seaborn 热图导出为完整的 pgf

python - 如何确定 matplotlib 轴是否已使用 axes.axis ('off' 关闭)?

jupyter-notebook - 你如何在 JupyterLab 中获取当前事件的笔记本名称?

python - 在 Jupyter iPython 中运行 Cython