简体   繁体   English

将全局设置应用于pyplot中的所有子图

[英]Apply global settings to all subplots in pyplot

This is related to this and this question. 这与这个问题有关。

I have a sequence of figures and subplots that have all very similar settings. 我有一系列的图和子图,它们都有非常相似的设置。 However, I can't seem to find a way to set them all at the same time. 但是,我似乎找不到找到同时设置它们的方法。 Here's a simplified version (I generally work with more instances): 这是一个简化的版本(我通常使用更多实例):

fspec = plt.figure(1)
spC = fspec.add_subplot(211)
spC.set_title('Surface concentrations')
spC.grid(True)
spC.set_ylim(1e-3, None)
spT = fspec.add_subplot(212, sharex=spC)
spT.set_title('Surface temperature')
spT.grid(True)
spT.set_ylim(1e-3, None)

fener = plt.figure(2)
enC = fener.add_subplot(211)
enC.set_title('Surface concentrations')
enC.grid(True)
enC.set_ylim(1e-3, None)
enT = fener.add_subplot(212, sharex=enC)
enT.set_title('Surface temperature')
enT.grid(True)
enT.set_ylim(1e-3, None)

I feel like there should be a way to apply something to every subplot open, or AT LEAST every subplot in a figure. 我觉得应该有一种方法可以对打开的每个子图应用某种东西,或者至少对图中的每个子图应用一些东西。 Something like 就像是

fspec.set_global_grid(True)
fspec.set_global_ylim(1e-3, None)

But I can't find it. 但是我找不到。

I took a look at some of the previous but none of them seem to work for me, since I don't work with one figure or axis at a time, I work with all of them kind of at the same time. 我看了一些以前的文章,但是似乎没有一个适合我,因为我一次不使用一个图形或轴,所以我会同时使用所有这些图形或轴。

Cheers. 干杯。

Some settings concerning mostly the style of the figure can be set globally using the matplotlib rc parameters . 可以使用matplotlib rc参数全局设置一些主要涉及图形样式的设置。 For example, setting the grid on throughout the script, put 例如,在整个脚本中设置网格,将

plt.rcParams['axes.grid'] = True

at the beginning of your file (after the imports). 在文件的开头(导入之后)。

Other things like axis limits are really specific to the plot itself, and there is no global parameter for that. 诸如轴限制之类的其他事情实际上是特定于图本身的,并且对此没有全局参数。 But you can still go the way, as outlined in the linked questions, ie write your own function that does most of the stuff you need. 但是您仍然可以按照链接的问题中的说明进行操作,即编写自己的函数来完成您需要的大多数工作。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['axes.grid'] = True

def plotfunction(fig, x1, y1, x2, y2,
                 title1 = 'Surface concentrations',
                 title2 = 'Surface temperature', **kwargs ):
    ax = fig.add_subplot(211)
    ax2 = fig.add_subplot(212, sharex=ax)
    ax.set_title(title1)
    ax2.set_title(title2)
    ax.set_ylim(1e-3, None)
    ax2.set_ylim(1e-3, None)
    ax.plot(x1, y1, **kwargs)
    ax2.plot(x2, y2, **kwargs)


fspec = plt.figure(1)
fener = plt.figure(2)

x1, y1, x2, y2 = np.loadtxt("spectrum.txt", unpack=True)
plotfunction(fspec,x1, y1, x2, y2)

x1, y1, x2, y2 = np.loadtxt("energy.txt", unpack=True)
plotfunction(fener,x1, y1, x2, y2, linewidth=3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM