【问题标题】:How to generate the same colors across two barcharts using Python matplotlib?如何使用 Python matplotlib 在两个条形图上生成相同的颜色?
【发布时间】:2021-04-20 10:39:53
【问题描述】:

我使用如下颜色图制作了一个水平条形图。此图表基于 DataFrame 中的values_1

我现在想使用values_2 制作第二个图表,但我正在尝试修复与第一个图表相关的颜色。例如L 在图表 2 中仍然是粉红色,与排序无关。

有没有办法生成这些颜色的字典并将其传递给 matplotlib 以用于下一个图表,例如 colors = {"M":[0.121569,0.466667,0.705882,1], "L":[0.682353,0.780392,0.909804,1]},或者可能是更好的方法?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

places = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]

df = pd.DataFrame(zip([15,12,22,11,14,13,17,19,16,14,19,11,10,13,17],[5,2,4,9,1,1,3,7,9,3,3,1,2,3,8]),
             index=places,columns=["values_1","values_2"])

df = df.sort_values('values_1',ascending=False)


colors = [i for i in [plt.get_cmap('tab20')(range(0,len(places)))]][0]

fig, ax  = plt.subplots(figsize=(10,5))
y_pos = np.arange(len(places))
ax.barh(y_pos,df["values_1"].sort_values(ascending=True),color=colors)
plt.yticks(y_pos,df.index)
plt.show()

【问题讨论】:

    标签: python pandas matplotlib charts colors


    【解决方案1】:

    您可以创建一个额外的列来存储第一次排序的顺序。然后您可以使用该顺序作为索引重新排序颜色:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    places = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"]
    num_p = len(places)
    
    df = pd.DataFrame({"values_1": [15, 12, 22, 11, 14, 13, 17, 19, 16, 14, 19, 11, 10, 13, 17],
                       "values_2": [5, 2, 4, 9, 1, 1, 3, 7, 9, 3, 3, 1, 2, 3, 8]},
                      index=places)
    df.sort_values('values_1', ascending=True, inplace=True)
    df["order1"] = np.arange(num_p)
    
    colors = plt.get_cmap('tab20')(range(0, num_p))
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
    
    y_pos = np.arange(num_p)
    ax1.barh(y_pos, df["values_1"], color=colors)
    ax1.set_yticks(y_pos)
    ax1.set_yticklabels(df.index)
    ax1.margins(y=0.02)
    ax1.set_title("values_1")
    
    df.sort_values('values_2', ascending=True, inplace=True)
    ax2.barh(y_pos, df["values_2"], color=colors[df["order1"]])
    ax2.set_yticks(y_pos)
    ax2.set_yticklabels(df.index)
    ax2.set_title("values_2")
    ax2.margins(y=0.02)
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 1970-01-01
      • 2016-02-04
      • 2018-11-28
      • 2020-11-04
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多