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

roc*_*eth 4 python numpy graph matplotlib

使用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()
Run Code Online (Sandbox Code Playgroud)

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

是否存在某种"figure1.legend(......")的东西?

谢谢.第一篇文章给我.你好,世界!;)

roi*_*ppi 6

如果您的子图实际上共享一个轴/某些轴,您可能有兴趣指定shareX=True和/或shareY=Truekwargs subplots.

请参阅John Hunter在此视频中解释更多内容.它可以使您的图形更清晰,减少代码重复.


A.W*_*Wan 2

我建议使用for循环:

for grph in [graphA, graphB]:
    grph.#edit features here
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

您必须考虑如何组织要绘制的数据以利用索引。合理?

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

  • @rockyourteeth 尝试 grph.set_xticks。 (2认同)