matplotlib 图例未显示 [英] matplotlib legend not showing
问题描述
我有两个 numpy 数据集并尝试制作两个图形(每个图形包括两个数据集).
I have two numpy datasets and trying to make two figures ( each figure including two datasets).
两个图例上均未显示图例.如果有人可以帮助我修复脚本,我将不胜感激
The legend does not show up on both figures. I´d appreciate if someone could help me fix the script,
预先感谢,
x=np.random.randint(0,10,(1000))
y=np.random.randint(5,15,(1000))
x_min=np.min(x)
x_max=np.max(x)
y_min=np.min(y)
y_max=np.max(y)
min_hist=min(x_min,y_min)
max_hist=max(x_max,y_max)
num_bins=30
bin_ranges= np.linspace(min_hist, max_hist, num_bins)
###### figure 1
fig, ax = plt.subplots()
ax.hist(x, color='lightblue', alpha=0.5, normed=True, bins=bin_ranges)
ax.hist(y, color='salmon', alpha=0.5, normed=True,bins=bin_ranges)
ax.set(title='including zero values ', ylabel='frequency')
ax.margins(0.05)
ax.set_ylim(bottom=0)
ax.legend()
fig.savefig(os.path.join(inputdir,"fig1.png"))
############################ figure 2
x_nonzero=x[np.nonzero(x)]
y_nonzero=y[np.nonzero(y)]
x_nonzero_min=np.min(x_nonzero)
x_nonzero_max=np.max(x_nonzero)
y_nonzero_min=np.min(y_nonzero)
y_nonzero_max=np.max(y_nonzero)
min_hist_nonzero=min(x_nonzero_min,y_nonzero_min)
max_hist_nonzero=max(x_nonzero_max,y_nonzero_max)
bin_ranges_nonzero= np.linspace(min_hist_nonzero, max_hist_nonzero, num_bins)
fig2, ax2 = plt.subplots()
ax2.hist(x_nonzero, color='lightblue', alpha=0.5, normed=True, bins=bin_ranges_nonzero)
ax2.hist(y_nonzero, color='salmon', alpha=0.5, normed=True,bins=bin_ranges_nonzero)
ax2.set(title='excluding zero values ', ylabel='frequency')
ax2.margins(0.05)
ax2.set_ylim(bottom=0)
ax2.legend()
fig2.savefig(os.path.join(inputdir,"fig2.png"))
plt.show()
推荐答案
当您说我无法使图例生效"时,我假设您的意思是没有图例出现.
When you say "I can not manage to make legend work" I am assuming you mean that no legend is showing up.
请考虑示例代码,这是一个非常简单的示例,就像您正在尝试绘制一个histgoram:
Consider the example code which is a very simple example of plotting a histgoram like you are trying to do:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(0,10,(1000))
fig,ax = plt.subplots()
ax.hist(data,bins=10,edgecolor='black')
ax.legend()
plt.show()
这将正确绘制图形,但是您的控制台中应该有一条警告说
This will draw the figure correctly, however there should be a warning in your console saying
C:\ Python27 \ lib \ site-packages \ matplotlib \ axes_axes.py:545:用户警告:未找到带标签的对象.使用label ='...'个别地块.warnings.warn(未找到带标签的对象."
C:\Python27\lib\site-packages\matplotlib\axes_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "
这是告诉您在 ax.hist()
因此,如果我们包括在内:
So if we include that:
ax.hist(data,bins=10,edgecolor='black',label="Entry 1")
我们得到以下图形:
这篇关于matplotlib 图例未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!