【问题标题】:Plotly: How to assign specific colors for categories? [duplicate]Plotly:如何为类别分配特定颜色? [复制]
【发布时间】:2021-01-13 17:19:16
【问题描述】:

我有一个发电组合的熊猫数据框。因此,它包括不同燃料的发电。我想为特定的燃料分配特定的颜色。 在 Matplotlib 中,通过传递颜色列表将特定颜色分配给特定类别很方便,例如

df.plot(kind="bar",color=["red","green","yellow"]

我无法使用 Plotly 为绘图分配类似的颜色。在 Plotly 中为特定类别分配特定颜色的最佳方法是什么?

【问题讨论】:

    标签: python python-3.x colors plotly plotly-python


    【解决方案1】:

    如果您的目标是为特定燃料分配特定颜色,那么color_discrete_sequence 可能对你很好,只要你的数据集的结构永远不会变化。但是最好通过以下方式指定每个类别的颜色:

    color_discrete_map = <dict>
    

    在你的情况下:

    fig = px.bar(df, color_discrete_map= {'Coal': 'black',
                                          'Oil': 'grey',
                                          'Gas': 'blue'}
                )
    

    这样您就不必依赖变量序列来匹配所需颜色的序列。

    示例图(使用不同但结构相同的数据集)

    完整代码

    import plotly.express as px
    import pandas as pd
    df = px.data.stocks().set_index('date')
    fig = px.bar(df, color_discrete_map= {'GOOG': 'black',
                                          'AAPL': 'grey',
                                          'AMZN': 'blue',
                                          'FB': 'green',
                                          'NFLX': 'red',
                                          'MSFT':'firebrick'}
                )
    fig.show()
    

    其他选项请查看Plotly: How to define colors in a figure using plotly.graph_objects and plotly.express??在那里,您将找到如何将颜色序列更改为您想要的任何颜色序列,并仍然通过color_discrete_map 指定一些异常。

    【讨论】:

    • 同意。这是最通用的方法
    【解决方案2】:

    从 plotly express 中的documentation on color sequences,您应该能够使用参数color_discrete_sequence 显式定义颜色序列。尝试运行:

    fig=px.bar(df1, title="Electricity generation mix of Germany in TwH (2000-2019)", color_discrete_sequence=["black","grey","lightgrey","red","rosybrown","blue","limegreen","yellow","forestgreen"])
    

    【讨论】:

    • 谢谢。它对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多