【问题标题】:How to graph two plots side by side using matplotlib (no pandas)如何使用 matplotlib 并排绘制两个图(无熊猫)
【发布时间】:2019-07-30 20:55:21
【问题描述】:

我完全脱离了自己的舒适区,但我被要求并排绘制一些数据。我设法将我的数据绘制成图表,但我不知道如何让它们并排绘制。我已经阅读了有关使用 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)

现在是这样输出的:

【问题讨论】:

    标签: python matplotlib jupyter-notebook data-science


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      绘制第一个图形时,写下这个

      plt.subplot(1, 2, 1)
      <code for first plot>
      

      (1,2,1) 表示此图是 1 行 2 列图和第一个图的一部分

      画第二个图的时候写这个

      plt.subplot(1, 2, 2)
      <code for second plot>
      

      (1,2,2) 表示此图是 1 行 2 列图和第 2 个图的一部分

      【讨论】: