【问题标题】:Apply global settings to all subplots in pyplot将全局设置应用于 pyplot 中的所有子图
【发布时间】:2017-06-16 04:42:51
【问题描述】:

这与thisthis 问题有关。

我有一系列具有非常相似设置的图形和子图。但是,我似乎无法找到同时设置它们的方法。这是一个简化版本(我通常使用更多实例):

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)

我觉得应该有一种方法可以将某些东西应用于每个打开的子图,或者至少是图中的每个子图。类似的东西

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

但我找不到。

我查看了之前的一些,但它们似乎都不适合我,因为我不是一次使用一个图形或轴,我同时使用所有这些。

干杯。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    可以使用matplotlib rc parameters 全局设置一些主要涉及图形样式的设置。 例如,在整个脚本中设置网格,把

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

    在文件的开头(在导入之后)。

    轴限制等其他内容确实特定于绘图本身,并且没有全局参数。但是您仍然可以按照链接问题中所述的方式进行操作,即编写您自己的函数来完成您需要的大部分内容。

    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)
    

    【讨论】:

    • matplotlib.rc 提示很好,但我不认为函数方法对我特别有效。有没有办法在全局范围内设置plt.legend(),就像你对网格所做的那样?
    • Legend 是特定于情节的,它包含情节的艺术家句柄;因此很明显它不能全局设置。但当然,您可以将其集成到功能中以自动设置。如果你不能详细说明为什么这种函数方法不适合你,我担心你在这里找不到什么帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    相关资源
    最近更新 更多