【问题标题】:Python customised title and legend in figure图中Python自定义标题和图例
【发布时间】:2014-11-02 06:41:05
【问题描述】:

我试图在我的人物顶部附近显示一个图例(如this)和上方的标题(如this

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,2850,3150,3400,3550,3800,3950,4050,4150,4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')
plt.text(0.5, 1.4, 'Data set A-1', 
        horizontalalignment='center', 
        fontsize=16,
        transform = ax.transAxes)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.25),
          ncol=3, fancybox=True, shadow=True)
#plt.tight_layout()
plt.show()

fig.savefig('test.pdf')

但是,当我保存此图表时,标题和图例都丢失了。只有坐标轴和数据点保存在 pdf 中。

【问题讨论】:

  • 您使用的是哪个版本的 Python?
  • Python 2.7.7、Spyder 2.3.0(但与 Spyder 无关)
  • 它们在上面,只是不在图中的视图中。尝试将图形调整为小,它们开始出现......
  • 如果您将 1.4 更改为 1.1,将 1.25 更改为 1.05,您将看到它们。
  • @Agean test.pdf 中的标题被(水平)切成两半。但是如果 1.4->1.05 和 1.25->1.05 和fontsize=14,那就没关系了...

标签: python matplotlib


【解决方案1】:

您正在将它们移出可见区域。如果你使用set_title mpl 会为你处理好它的位置。与图例上的边界框相同:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,2850,3150,3400,3550,3800,3950,4050,4150,4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')
ax.set_title('Data set A-1')

ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)

ax.legend(loc='upper center', 
          ncol=3, fancybox=True, shadow=True)
#plt.tight_layout()
plt.show()

您可能还想将 num_points=1 作为 kwarg 传递给 legend

【讨论】:

    【解决方案2】:

    你想让图例也出现在坐标轴上吗?

    #!/usr/bin/python3
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.arange(1,24,1)
    y = np.array([400,650,1020,1300,1600,1950,2200,2550,
                  2850,3150,3400,3550,3800,3950,4050,4150,
                  4210,4250,4300,4320,4310,4300,4200])
    
    fig = plt.figure()
    ax = plt.subplot(111)
    
    ax.plot(x,y,'o', label='data set 1')
    
    ax.set_xlabel('x', fontsize=14)
    ax.set_ylabel('y', fontsize=14)
    ax.set_ylim(ymax=5000)
    
    
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
              ncol=3, fancybox=True, shadow=True)
    title = ax.set_title('Data set A-1')
    
    fig.tight_layout()
    
    fig.subplots_adjust(top=0.85)
    title.set_y(1.07)
    
    fig.savefig("13.png")
    

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多