简体   繁体   中英

Adding legend to a plotted histogram

How can I a menage to add a label to a histogram, after its plotting?

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
x = [2, 4, 6, 2, 4, 7, 6, 4, 4, 4, 4]

n, bins_edges, patches = ax1.hist(x, log=True, bins='doane', color="red")
binwidth =  bins_edges[1] - bins_edges[0]
mylabel = "Binwidth {}".format(binwidth)
ax1.hist[-1].set_label(mylabel)
plt.legend()
plt.show()

You can add string to legend by passing it to legend()

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
x = [2, 4, 6, 2, 4, 7, 6, 4, 4, 4, 4]

n, bins_edges, patches = ax1.hist(x, log=True, bins='doane', color="red")
binwidth =  bins_edges[1] - bins_edges[0]
mylabel = "Binwidth {}".format(binwidth)


ax1.legend([mylabel])
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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