【问题标题】:How to use a color map and have a specific color for a certain value on a stacked bar using matplotlib如何使用颜色图并在使用 matplotlib 的堆叠条上为某个值指定特定颜色
【发布时间】:2019-12-01 09:00:07
【问题描述】:

我正在创建一个堆积条形图,以显示不同“位置”上不同“事件”的频率[每个位置都是一个条形,并由那里发生的事件分割]。我希望每个事件都有一个独特的颜色并且可以区分,所以我想使用彩虹颜色图。但是最后的事件我想是白色的。

到目前为止,我只有使用 Rainbow 进行绘图的代码,最后一个事件显示为红色。我怎样才能让它变白呢?

import pandas as pd
import matplotlib as plt
from matplotlib import cm
import numpy as np

r = [0,1,2,3]
raw_data = {'1': [20, 5, 3, 2], '2': [5, 15, 5, 4],'3': [3, 5, 13, 17], '4': [2, 3, 7, 5], '5':[5, 7, 7, 7]}
df = pd.DataFrame(raw_data)
event_colours = plt.cm.rainbow(np.linspace(0, 1, 5))
sbc = df.plot.bar(stacked = True, color = event_colours)
sbc.set(xlabel="Position", ylabel="Frequency")
sbc.legend(loc='center right', bbox_to_anchor=(-0.2, 0.5))

【问题讨论】:

  • 你打算如何在白色背景上看到白色条?

标签: python pandas matplotlib colors colormap


【解决方案1】:

将最后一种颜色设置为白色,例如通过event_colours[-1] = (1,1,1,1)

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

r = [0,1,2,3]
raw_data = {'1': [20, 5, 3, 2], '2': [5, 15, 5, 4],'3': [3, 5, 13, 17], 
            '4': [2, 3, 7, 5], '5':[5, 7, 7, 7]}
df = pd.DataFrame(raw_data)
event_colours = plt.cm.rainbow(np.linspace(0, 1, 5))
event_colours[-1] = (1,1,1,1)

ax = df.plot.bar(stacked = True, color = event_colours, edgecolor="k")
ax.set(xlabel="Position", ylabel="Frequency")
ax.legend(loc='center right', bbox_to_anchor=(-0.2, 0.5))
ax.figure.subplots_adjust(left=0.3)


plt.show()

【讨论】:

    【解决方案2】:

    一种解决方案是通过使用patches 访问它们来简单地更改最顶部条的颜色。然后,更新相应的图例条目。另一种可能的解决方案是创建自定义颜色图。

    由于白色背景上的白色条不可见,因此我选择了lightgrey 颜色来演示我的解决方案。

    # Your 4 import commands here
    import matplotlib.patches as mpatches
    
    # Your code goes here
    # ............
    
    # Change the color of the last 4 bars
    for patch in list(sbc.axes.patches)[-4:]:
        patch.set_facecolor('lightgrey')
    
    # Update the legend entry
    hans, labs = sbc.get_legend_handles_labels() # Get the existing legends
    last_bar = mpatches.Patch(color='lightgrey', label='5')
    del labs[-1], hans[-1] # Delete the last red legend entry
    
    hans.append(last_bar) # add the grey bar to the legend
    sbc.legend(handles=hans, loc=2, bbox_to_anchor=(-0.3, 0.7))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2015-12-28
      • 2021-10-30
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多