使用matplotlib,是否可以一次为图中的所有子图设置属性?

6
使用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”设置和“legend”设置有点繁琐。

是否有一种类似于“figure1.legend(...”之类的方法呢?

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


是的,有一个 figure1.legend。尝试使用 help(figure1.legend) 以获取详细信息。 - esmit
2个回答

7
如果你的子图实际上共享一个或多个轴,你可能会对在subplots中指定sharex=True和/或sharey=True参数感兴趣。详见John Hunter在这个视频中的解释。这能让你的图表看起来更整洁,并减少代码重复。

1
谢谢。我经常自己回去看它;原来库的创建者对如何使用它有一些了解。 :) - roippi

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)。 - rockyourteeth
1
嗯,这就是为什么我倾向于在单个“for”循环中编写整个绘图过程的原因,这样您就可以创建一个新的子图并立即更改其设置。但是,如果这不可行(例如,您正在解释器窗口中工作),则可以通过执行subplot(xxx)来调用所需的子图,无论您想要编辑哪个子图。然后xticks应该会编辑那个子图。这是我最好的猜测。 - A.Wan
2
@rockyourteeth 尝试使用 grph.set_xticks。 - esmit
@esmit,嘿谢谢!那绝对是我最初需要的。看起来与grph.set_xticklabels一起使用可以实现我所需的功能。 - rockyourteeth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接