在matplotlib中单独设置颜色

时间:2016-06-21 16:32:01

标签: numpy pandas matplotlib

我想创建一个自定义图。我想精确指定每个对象的颜色。具体来说,我正在为系统事件创建甘特图。我将这些事件分组并对它们进行颜色编码以便可视化。

请考虑以下代码:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame()
df['y'] = [0,4,5,6,10]
df['color'] = [(.5, .5, .5, .5),]*len(df)
print df['color']

#fig = plt.figure(figsize=(12, 6))
#vax = fig.add_subplot(1,1,1)
#vax.hlines(df['y'], 0, 10, colors=df['color'])
#fig.savefig('ok.png')

only_four = df['y']==4
df['color'][only_four] = [(0.7, 0.6, 0.5, 0.4),]*sum(only_four)
print df['color']

请注意,我首先将所有颜色设置为半透明灰色。后来,对于一组特定的值,我想改变颜色。我最终得到了这张颜色表。

0    (0.5, 0.5, 0.5, 0.5)
1                     0.6
2    (0.5, 0.5, 0.5, 0.5)
3    (0.5, 0.5, 0.5, 0.5)
4    (0.5, 0.5, 0.5, 0.5)

我希望能够为任何hlines子集指定任何RGBA值(即包括透明度)。有人可以分享如何做到这一点?我可以采用任何其他方式来做到这一点,只要我能为每一行精确着色,包括透明度。

补充问题: 我可以通过迭代更新多行,如下所示:

def set_color(df, row_bool, r, g, b, a=1.0):
    idx = np.where(row_bool)[0]
    for i in idx:
        df['color'][i] = (r,g,b,a)
    return

这已经足够了,但我真的想要一个向量操作(即我没有显式循环)。

1 个答案:

答案 0 :(得分:0)

我猜测问题是你无法将更新后的元组输入到DataFrame中,而只能在DataFrame中获得0.6值。您是否尝试过使用DataFrame.set_value

In [1]: df
Out[1]: 
    y                 color
0   0  (0.5, 0.5, 0.5, 0.5)
1   4                   0.6
2   5  (0.5, 0.5, 0.5, 0.5)
3   6  (0.5, 0.5, 0.5, 0.5)
4  10  (0.5, 0.5, 0.5, 0.5)

In [2]: df.set_value(1, 'color', (0.7, 0.6, 0.5, 0.4))
Out[2]: 
    y                 color
0   0  (0.5, 0.5, 0.5, 0.5)
1   4  (0.7, 0.6, 0.5, 0.4)
2   5  (0.5, 0.5, 0.5, 0.5)
3   6  (0.5, 0.5, 0.5, 0.5)
4  10  (0.5, 0.5, 0.5, 0.5)