简体   繁体   English

更改Python直方图的图例格式

[英]Change the legend format of Python histogram

I label the two different histograms in the same figure, as shown below. 我在同一张图中标记了两个不同的直方图,如下所示。 However, the legend for the two histograms are in the format of a box. 但是,两个直方图的图例采用的是方框格式。 I tried various ways to change the box to line but all did not work. 我尝试了多种方法来将框更改为行,但是所有方法均无效。 I wonder how to implement such function? 我想知道如何实现这样的功能? 在此处输入图片说明

One way to go about doing this is to specify explicitly the legend handles by hand: 进行此操作的一种方法是手动明确指定图例句柄:

handle1 = matplotlib.lines.Line2D([], [], c='r')
handle2 = matplotlib.lines.Line2D([], [], c='b')
plt.legend(handles=[handle1, handle2])

Depending of course a good deal on how you set everything up, this might look as follows: 当然,取决于如何设置所有内容,这看起来可能如下所示:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

# Generate some data that sort of looks like that in the question
np.random.seed(0)
x1 = np.random.normal(2, 1, 200)
x2 = np.random.exponential(1, 200)

# Plot the data as histograms that look like unfilled lineplots
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(x1, label='target', histtype='step')
ax.hist(x2, label='2nd halo', histtype='step')

# Create new legend handles but use the colors from the existing ones
handles, labels = ax.get_legend_handles_labels()
new_handles = [Line2D([], [], c=h.get_edgecolor()) for h in handles]

plt.legend(handles=new_handles, labels=labels)
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM