Python 自定义图形标题和图例
我想在我的图表顶部附近显示一个图例(就像这个),并在它上面加一个标题(就像这个)
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里只有坐标轴和数据点。
2 个回答
1
你想要图例也显示在坐标轴上吗?
#!/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")
3
你把它们移出了可见区域。如果你使用 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()
你可能还想在调用 legend
时传入 num_points=1
作为一个关键字参数。