【问题标题】:Using matplotlib, is it possible to set properties for all subplots on a figure at once?使用 matplotlib,是否可以一次为图形上的所有子图设置属性?
【发布时间】:2013-07-19 04:05:38
【问题描述】:

使用matplotlib(与Python),是否可以一次为图形上的所有子图设置属性?

我创建了一个包含多个子图的图形,目前我有这样的东西:

import numpy as np
import matplotlib.pyplot as plt

listItems1 = np.arange(0, 100)
listItems8 = np.arange(0, 100)
listItems11 = np.arange(0, 100)
figure1 = plt.figure(1)

# First graph on Figure 1
graphA = figure1.add_subplot(2, 1, 1)
graphA.plot(listItems1, listItems8, label='Legend Title')
graphA.legend(loc='upper right', fontsize='10')
graphA.grid(True)
plt.xticks(range(0, len(listItems1) + 1, 36000), rotation='20', fontsize='7', color='white', ha='right')
plt.xlabel('Time')
plt.ylabel('Title Text')

# Second Graph on Figure 1
graphB = figure1.add_subplot(2, 1, 2)
graphB.plot(listItems1, listItems11, label='Legend Title')
graphB.legend(loc='upper right', fontsize='10')
graphB.grid(True)
plt.xticks(range(0, len(listItems1) + 1, 36000), rotation='20', fontsize='7', color='white', ha='right')
plt.xlabel('Time')
plt.ylabel('Title Text 2')

plt.show()

问题,有没有办法一次设置任何或所有这些属性?我将在一个图中有 6 个不同的子图,一遍又一遍地复制/粘贴相同的“xticks”设置和“图例”设置有点乏味。

有没有“figure1.legend(...”之类的东西?

谢谢。给我的第一篇文章。你好世界! ;)

【问题讨论】:

  • 是的,有一个figure1.legend。详情请尝试help(figure1.legend)

标签: python graph numpy matplotlib


【解决方案1】:

如果您的子图实际上共享一个轴/一些轴,您可能有兴趣将sharex=True 和/或sharey=True kwargs 指定为subplots

请参阅 John Hunter 在this video 中解释更多信息。它可以使您的图表看起来更清晰,并减少代码重复。

【讨论】:

  • 谢谢!那个视频很棒!
  • 干杯。我经常自己回去;事实证明,图书馆的创建者知道如何使用它的一两件事。 :)
【解决方案2】:

我建议使用for 循环:

for grph in [graphA, graphB]:
    grph.#edit features here

您还可以根据自己的需要以不同的方式构建 for 循环,例如

graphAry = [graphA, graphB]
for ind in range(len(graphAry)):
    grph = graphAry[ind]
    grph.plot(listItems1, someList[ind])
#etc

关于子图的好处是您也可以使用for 循环来绘制它们!

for ind in range(6):
    ax = subplot(6,1,ind)
    #do all your plotting code once!

您必须考虑如何组织要绘制的数据以利用索引。有意义吗?

每当我做多个子图时,我都会考虑如何为它们使用for 循环。

【讨论】:

  • 好的,谢谢。这很有帮助!还有一件事:“xticks”似乎不接受命名图作为前缀。我不能告诉它要编辑哪个图形,它只是编辑它上面的图形。有没有办法指定正在编辑哪个图形“xticks”?因为现在如果我尝试将其放入 for 循环(AttributeError)中会出现错误。
  • 嗯,这就是为什么我倾向于在单个 for 循环中编写整个绘图过程,以便您制作一个新的子图并立即更改其设置。但如果这是不切实际的(例如,您正在解释器窗口中工作),您可以通过执行 subplot(xxx) 来调用您想要的子图,无论您要编辑哪个。然后 xticks 应该编辑那个。这是我最好的猜测。
  • @rockyourteeth 试试 grph.set_xticks。
  • @esmit,嘿,谢谢!这绝对是我首先需要的。看起来将它与 grph.set_xticklabels 一起使用可以完成我所需要的。
猜你喜欢
  • 2021-08-09
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多