【问题标题】:Plotly: How to use the same colors for categories of two different plots?Plotly:如何为两个不同地块的类别使用相同的颜色?
【发布时间】:2021-09-13 10:37:06
【问题描述】:

我正在尝试为类别创建两个具有相同配色方案的图。然而,这些图使用不同的颜色模式,我似乎无法解决这个问题:

.

如何强制 plotly 对两个图表使用相同的颜色?非常感谢任何帮助!

Image

【问题讨论】:

    标签: python plotly data-visualization visualization plotly-python


    【解决方案1】:

    plotly.express 饼图和条形图的color_discrete_map 属性可用于为列设置显式颜色值。

    饼图的用法示例:

    import plotly.express as px
    df = px.data.tips()
    fig = px.pie(df, values='tip', names='day', color='day',
                 color_discrete_map={'Thur':'lightcyan',
                                     'Fri':'cyan',
                                     'Sat':'royalblue',
                                     'Sun':'darkblue'})
    fig.show()
    

    条形图的示例用法:

    import plotly.express as px
    df = px.data.gapminder().query("year == 2007")
    fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
                 color_discrete_map={
                    "Europe": "red",
                    "Asia": "green",
                    "Americas": "blue",
                    "Oceania": "goldenrod",
                    "Africa": "magenta"},
                 title="Explicit color mapping")
    
    fig.show()
    

    【讨论】:

      【解决方案2】:

      定义一个离散的颜色图。在下面的代码中:c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))

      import pandas as pd
      import numpy as np
      import plotly.express as px
      
      # create some data
      df = pd.DataFrame({"date":np.random.choice(pd.date_range("1-sep-2020","31-Dec-2020"),300),
                   "emotion":np.random.choice(["positive","negative","anticipation","fear","trust"], 300)}).sort_values("date")
      
      # map emotions to a color
      c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))
      
      # bar chart
      px.bar(
          df.groupby(["date", "emotion"], as_index=False)
          .size()
          .rename(columns={"size": "count"}),
          x="date",
          y="count",
          color="emotion",
          color_discrete_map=c
      ).show()
      
      # pie chart
      px.pie(
          df.groupby("emotion", as_index=False).agg(
              perc=("date", lambda s: len(s) / len(df))
          ),
          values="perc",
          names="emotion",
          color="emotion",
          color_discrete_map=c
      ).show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        • 2019-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多