gpt4 book ai didi

dictionary - matplotlib 条形图从类别数据框列添加图例

转载 作者:行者123 更新时间:2023-12-03 15:26:34 24 4
gpt4 key购买 nike

我尝试添加图例,根据我的示例,它应该输出:

  • 一个红色方块,上面写着水果和
  • 一个带有单词的绿色方块
    蔬菜。

  • 我尝试了几件事(下面的例子只是众多试验中的一项),但我无法让它工作。

    有人能告诉我如何解决这个问题吗?
    import pandas as pd
    from matplotlib import pyplot as plt
    data = [['apple', 'fruit', 10], ['nanaba', 'fruit', 15], ['salat','veggie', 144]]
    data = pd.DataFrame(data, columns = ['Object', 'Type', 'Value'])

    colors = {'fruit':'red', 'veggie':'green'}
    c = data['Type'].apply(lambda x: colors[x])

    bars = plt.bar(data['Object'], data['Value'], color=c, label=colors)
    plt.legend()

    plot

    最佳答案

    为不在轴中的对象创建图例的常用方法是创建代理艺术家,如 legend guide 所示。

    这里,

    colors = {'fruit':'red', 'veggie':'green'}         
    labels = list(colors.keys())
    handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]
    plt.legend(handles, labels)

    enter image description here

    关于dictionary - matplotlib 条形图从类别数据框列添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57340415/

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