【问题标题】:Python 3 figure subplot only shows one plotPython 3 图形子图仅显示一个图
【发布时间】:2015-12-28 18:34:23
【问题描述】:

我有以下代码,其中只有 ax3 显示绘图区域和数据。子图 ax1 和 ax2 显示绘图区域但没有数据。最终,我想要三个带有 sharex=True 的图(3、1 配置)。我正在使用 Python 2.7.2 和 matplotlib 1.2.1

import numpy as np
import matplotlib.pyplot as plt

f, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, sharey=False)
f.subplots_adjust(wspace=0)

N = 4
ind = np.arange(N)

width = .4
group_names = ('A', 'B', 'C', 'D')

q2 = [84, 21, 10, 4]
q4 = [69, 34, 22, 0]
q6 = [66, 28, 17, 2]

colors = ['c', 'purple', 'g', 'red']

ax1 = plt.barh(ind, q2, width, color=colors)
plt.yticks(ind+width/N, group_names)
plt.ylim([min(ind)-0.25, max(ind)+0.65])
plt.xticks(np.arange(0, 110, 10.))
plt.xlim(0, 100)

ax2 = plt.barh(ind, q4, width, color=colors)
plt.yticks(ind+width/N, group_names)
plt.ylim([min(ind)-0.25, max(ind)+0.65])
plt.xticks(np.arange(0, 110, 10.))
plt.xlim(0, 100)

ax3 = plt.barh(ind, q6, width, color=colors)
plt.yticks(ind+width/N, group_names)
plt.ylim([min(ind)-0.25, max(ind)+0.65])
plt.xticks(np.arange(0, 110, 10.))
plt.xlim(0, 100)

plt.show()

【问题讨论】:

  • 为什么在这里使用plt.barh?而是使用ax1.barh 等直接绘制到您的轴上。
  • 顺便说一句,matplotlib v1.2.1 已经两岁半了。 1.4.3 是当前的稳定版本。您可能会考虑更新您的版本

标签: python matplotlib subplot


【解决方案1】:

你做了一些有点奇怪的事情。您可以使用plt.subplots 命令在脚本顶部定义ax1ax2ax3,但以后不再使用它们。我已经重新编写了您的脚本,以确保您的所有命令都在正确的axes 上运行。

您可以使用ax1.barh(),而不是plt.barh()。然后,您可以使用ax1.set_yticks()ax1.set_ylim()ax1.set_xticks()ax1.set_xlim() 设置刻度和坐标轴范围

import numpy as np
import matplotlib.pyplot as plt

f, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, sharey=False)
f.subplots_adjust(wspace=0)

N = 4
ind = np.arange(N)

width = .4
group_names = ('A', 'B', 'C', 'D')

q2 = [84, 21, 10, 4]
q4 = [69, 34, 22, 0]
q6 = [66, 28, 17, 2]

colors = ['c', 'purple', 'g', 'red']

ax1.barh(ind, q2, width, color=colors)
ax1.set_yticks(ind+width/N, group_names)
ax1.set_ylim([min(ind)-0.25, max(ind)+0.65])
ax1.set_xticks(np.arange(0, 110, 10.))
ax1.set_xlim(0, 100)

ax2.barh(ind, q4, width, color=colors)
ax2.set_yticks(ind+width/N, group_names)
ax2.set_ylim([min(ind)-0.25, max(ind)+0.65])
ax2.set_xticks(np.arange(0, 110, 10.))
ax2.set_xlim(0, 100)

ax3.barh(ind, q6, width, color=colors)
ax3.set_yticks(ind+width/N, group_names)
ax3.set_ylim([min(ind)-0.25, max(ind)+0.65])
ax3.set_xticks(np.arange(0, 110, 10.))
ax3.set_xlim(0, 100)

plt.show()

【讨论】:

    【解决方案2】:

    而不是使用

        plt.barh(ind, q2, width, color=colors)
    

    把它们改成

        ax1 = ax1.barh(ind, q2, width, color=colors)
        ax2 = ax2.barh(ind, q4, width, color=colors)
        ax3 = ax3.barh(ind, q6, width, color=colors)
    

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      相关资源
      最近更新 更多