首页 > 解决方案 > 使用默认颜色图绘制数据框的列,但使用不同颜色的一列除外

问题描述

我在数据框中有一大堆列,我正在绘制如下:

df.xs('Mean', level=1).cumsum().plot(cmap='winter').

这绘制了我所有列的平均值随时间的累积总和。(0级多索引是时间)但是,我想用不同的颜色突出显示图中的特定列,但我不确定如何去做。像这样的东西:

df.xs('Mean', level=1).cumsum().plot(cmap='winter', color={'my_specific_column':'red'}).

这将绘制沿'winter'cmap 光谱的所有其他列(蓝绿色到蓝色),除了'my_specific_column',它将是红色的。

有任何想法吗?

标签: pythonpandasmatplotlibplotcolors

解决方案


这是另一种解决方案。首先,我们从颜色图中获取颜色,并将它们设置为我们想要绘制的每一列。我们通过强制使用我们想要的颜色来更新字典。最后,我们设置了要应用于绘图的地图。

import matplotlib
cmap = matplotlib.cm.get_cmap('winter')

# get colors for each of the columns
columns = df.columns.values
colors = [cmap(i) for i in range(1, len(columns)+1)]

# build a dictionary with them
COLORS_DICT = dict(zip(columns, colors))

# update with the column we want to change
COLORS_DICT.update({"my_specific_column": 'red'})
COLORS_MAP = list(map(lambda x : COLORS_DICT[x], COLORS_DICT))
df[columns].plot(color=COLORS_MAP)

推荐阅读