gpt4 book ai didi

python - 向直方图添加图例/图例

转载 作者:行者123 更新时间:2023-11-30 22:19:16 25 4
gpt4 key购买 nike

我无法向使用 matplotlib.pyplot 创建的直方图添加图例。希望得到一些帮助/建议。

下面的数据集是垃圾数据,但却是这种情况的准确示例,两个数据集都在同一数据框中,由列上的过滤器分隔。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import pyodbc
import re


data = [{ 'uid':1,'Region':'nebraska', 'metric1':24},
{ 'uid':2,'Region':'nebraska', 'metric1':12},
{ 'uid':3,'Region':'nebraska', 'metric1':23},
{ 'uid':4,'Region':'nebraska', 'metric1':12},
{ 'uid':1,'Region':'nebraska', 'metric1':24},
{ 'uid':2,'Region':'nebraska', 'metric1':12},
{ 'uid':3,'Region':'nebraska', 'metric1':23},
{ 'uid':4,'Region':'nebraska', 'metric1':12},
{ 'uid':1,'Region':'nebraska', 'metric1':24},
{ 'uid':2,'Region':'nebraska', 'metric1':12},
{ 'uid':3,'Region':'nebraska', 'metric1':23},
{ 'uid':4,'Region':'nebraska', 'metric1':12},
{ 'uid':1,'Region':'nebraska', 'metric1':24},
{ 'uid':2,'Region':'nebraska', 'metric1':12},
{ 'uid':3,'Region':'nebraska', 'metric1':23},
{ 'uid':4,'Region':'nebraska', 'metric1':12},
{ 'uid':29,'Region':'colorado', 'metric1':14},
{ 'uid':30,'Region':'colorado', 'metric1':45},
{ 'uid':30,'Region':'colorado', 'metric1':45},
{ 'uid':30,'Region':'colorado', 'metric1':45},
{ 'uid':31,'Region':'colorado', 'metric1':65},
{ 'uid':32,'Region':'colorado', 'metric1':50}
]

testDataset = pd.DataFrame(data)

b = np.arange(0,100, 50)


plt.hist(testDataset[testDataset['Region'] == 'nebraska']['metric1'], b,color = 'red')
plt.xticks(rotation=90)
plt.xticks(np.arange(0, 100, 10))
plt.yticks(np.arange(0, 100, 10))
plt.grid(zorder=0)


plt.hist(testDataset[testDataset['Region'] == 'colorado']['metric1'], b,color = 'blue')

plt.show()

最佳答案

只需向您的 hist 调用添加一个 label 参数即可:

plt.hist(testDataset[testDataset['Region'] == 'nebraska']['metric1'], b,
color = 'red', label='Nebraska')
plt.hist(testDataset[testDataset['Region'] == 'colorado']['metric1'], b,
color = 'blue', label='Colorado')

并在plt.show()之前调用plt.legend()

关于python - 向直方图添加图例/图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49178622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com