python - Matplotlib,图例未出现在直方图中

标签 python pandas matplotlib histogram legend

为了描述我的问题,我为您提供了一个小数据集作为示例:想象一下以下数据集:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'name':['a', 'b', 'c', 'a', 'b', 'c'], 'val':[1,5,3,4,5,3]} )

我正在使用以下代码创建简单的直方图:

def plot_bar_x():
    index = np.arange(len(df['name']))
    plt.bar(index, df['val'])
    plt.legend(list(df['name'].unique()))
    plt.xticks(index, df['name'], fontsize=10, rotation=30)
    plt.show()
plot_bar_x()

但它给了我以下情节: enter image description here

虽然我有 3 个唯一的名称,但我只看到“a”标签,但是我使用了这一行:plt.legend(list(df['name'].unique())) 另一个问题是所有的条都是相同的颜色,有没有办法在不事先手动定义颜色的情况下为独特的标签获得不同的颜色?

期望的输出是:

enter image description here

最佳答案

你只能在一个系列上绘制一次,这就是为什么 plt 只为图例选择一个标签。如果您没有很多名字,请尝试:

def plot_bar_x():
    index = np.arange(len(df['name']))
    plt.figure()
    for name in df.name.unique():
        tmp_df = df[df.name == name]
        plt.bar(tmp_df.index, tmp_df.val, label=name)
    plt.xticks(index, df['name'], fontsize=10, rotation=30)
    plt.legend()
    plt.show()

一定有一些聪明的方法可以解决您的问题,但现在我无法解决。

关于python - Matplotlib,图例未出现在直方图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885970/

相关文章:

python - 如何在Python中的单个列表中根据给定的x,y值绘制不同的线?

python - 列表的哪些元素进入哪个直方图箱?

python - 在 VS Code 中,我不想让 Black 格式化我的 settings.json

python - 如何在python中输入

python - 有条件地重命名多个列名称

python - Pandas 合并索引不起作用

Python-如何使用 scikit 创建将数据拆分为训练和验证的函数

python - 静音来自 'import pandas' 语句的 DEBUG 警报

python - 两个不同数据帧(dfs)中单词之间的字符串文字匹配并生成一个新的数据帧

python - 哪些版本的 NumPy 与 Python 3.3 兼容?