【问题标题】:Adjusting graphs with Matplotlib使用 Matplotlib 调整图形
【发布时间】:2019-05-13 15:17:06
【问题描述】:

我在调整图表 y 轴上数字标签的字体大小时遇到​​了一些问题。调整字体大小似乎只是调整图例框中的文字。

调整“轴”不起作用,因为我使用了axes.ravel() 来帮助给出一组 2x2 的四个子图。

"axes.set_xlabel(fontsize='large', fontweight='bold') 属性错误: 'numpy.ndarray' 对象没有属性 'set_xlabel'"

#The part of the code that creates the subplots.

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(40,20), squeeze=False, sharey=True)
axes = axes.ravel()

font = FontProperties()

font = {'weight' : 'bold','size'   : 22}

plt.rc('font', **font)

#Then under here are the loops that create each subplot.

for each_subplot in range(0,4):

    axes.set_xlabel(fontsize='large', fontweight='bold')

#Selecting the input data goes here, but I left it out.

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    axes 本身就是一个轴数组。所以你想做:

    for each_subplot in range(0,4):
        axes[each_subplot].set_xlabel(fontsize='large', fontweight='bold')
    

    或更简单:

    for ax in axes:
        ax.set_xlabel(fontsize='large', fontweight='bold')
    

    【讨论】:

    • 我想我已经解决了部分问题,我想让 y 轴刻度上的数字具有更大的字体,我认为这与 axes.set_ylabel() 不同。这可能吗?
    【解决方案2】:

    axes现在是一个ndarray,所以你需要从数组中提取元素并调用set_xlabel()方法。试试这个。

    for each_subplot in range(0,4):
        axes[each_subplot].set_xlabel(fontsize='large', fontweight='bold')
    

    【讨论】:

      【解决方案3】:

      在这种情况下,我个人建议使用enumerate,它不仅可以让您访问各个轴对象,还可以访问可用于修改标签的索引,例如。要展平axes,您可以使用axes.ravel()axes.flatten()。另外,您可以直接在enumerate中使用axes.flatten(),如下所示。

      fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8,5), squeeze=False, sharey=True)
      
      for index, ax in enumerate(axes.ravel()):
          ax.set_xlabel('X-label %s' %index, fontsize='large', fontweight='bold')
      plt.tight_layout()    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2015-04-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        • 2010-11-19
        相关资源
        最近更新 更多