在使用matplotlib以正确的格式显示图例时,我面临一个问题。
编辑:我在一个2乘2格式的图形中有4个子图,我只想要第一个子图上有两行画的图例。我使用下面所附的代码获得的图例包含了无穷无尽的条目,并垂直扩展到整个图中。当我使用相同的代码使用linspace生成假数据时,图例工作得非常好。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import os
#------------------set default directory, import data and create column output vectors---------------------------#
path="C:/Users/Pacman/Data files"
os.chdir(path)
data =np.genfromtxt('vrp.txt')
x=np.array([data[:,][:,0]])
y1=np.array([data[:,][:,6]])
y2=np.array([data[:,][:,7]])
y3=np.array([data[:,][:,9]])
y4=np.array([data[:,][:,11]])
y5=np.array([data[:,][:,10]])
nrows=2
ncols=2
tick_l=6 #length of ticks
fs_axis=16 #font size of axis labels
plt.rcParams['axes.linewidth'] = 2 #Sets global line width of all the axis
plt.rcParams['xtick.labelsize']=14 #Sets global font size for x-axis labels
plt.rcParams['ytick.labelsize']=14 #Sets global font size for y-axis labels
plt.subplot(nrows, ncols, 1)
ax=plt.subplot(nrows, ncols, 1)
l1=plt.plot(x, y2, 'yo',label='Flow rate-fan')
l2=plt.plot(x,y3,'ro',label='Flow rate-discharge')
plt.title('(a)')
plt.ylabel('Flow rate ($m^3 s^{-1}$)',fontsize=fs_axis)
plt.xlabel('Rupture Position (ft)',fontsize=fs_axis)
# This part is not working
plt.legend(loc='upper right', fontsize='x-large')
#Same code for rest of the subplots但是,我试图实现以下链接中建议的修补程序,但无法使其工作:how do I make a single legend for many subplots with matplotlib?
在这方面的任何帮助都将受到高度赞赏。
发布于 2016-06-15 17:50:24
在处理子图时,直接使用轴(在您的情况下是ax)是很有用的。因此,如果你在一个图形中设置了两个情节,并且只希望在你的第二个情节中有一个传奇:
t = np.linspace(0, 10, 100)
plt.figure()
ax1 = plt.subplot(2, 1, 1)
ax1.plot(t, t * t)
ax2 = plt.subplot(2, 1, 2)
ax2.plot(t, t * t * t)
ax2.legend('Cubic Function')注意,在创建图例时,我是在ax2上这样做的,而不是在plt上。如果您希望为第一个子图创建第二个图例,则可以在ax1上以同样的方式进行。
发布于 2016-06-15 17:51:52
如果我的理解正确,你需要告诉plt.legend什么是传说.此时,它正在被加载为空。你得到的肯定是另一个来源。我有以下内容,当然,当我像您一样运行fig.legend时,我什么也得不到。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1, l2 = ax1.plot(x, y1, 'rs-', x, y2, 'go')
y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax2.plot(x, y3, 'yd-', x, y4, 'k^')
fig.legend(loc='upper right', fontsize='x-large')
#fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')
#fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
plt.show()我建议一个接一个地做,然后申请所有人。
https://stackoverflow.com/questions/37842064
复制相似问题