繁体   English   中英

如何根据数据框(pandas)中的值设置条形(matplotlib)的颜色?

[英]How can I set the color of a bar (matplotlib) according to a value in a dataframe (pandas)?

我想从数据框创建条形图。 但我想根据数据框中“红色”列中的值为每个条着色。 我有以下代码:

plt.bar(df.index, df['Mean'], yerr = df['yerr'], capsize=7, color = (df['red'], 0, 0, 0.6))

我想从列“ red”(从0到1)中取值,但是它一直失败。 你会怎么做?

这样的事情会起作用。 您必须创建具有共同长度的蓝色,绿色和alpha列,然后将它们与红色一起压缩。

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

data = [
    [1, 1, 0.1],
    [2, 1, 0.2],
    [3, 1, 0.3],
    [4, 1, 0.4],
    [5, 1, 0.5],
    [6, 1, 0.6],
    [7, 1, 0.7],
    [8, 1, 0.8],
    [9, 1, 0.9],
]
columns = ['Mean', 'yerr', 'red']
df = pd.DataFrame(data=data, columns=columns)

r = df['red']
g = np.zeros(r.shape[0])
b = np.zeros(r.shape[0])
a = np.ones(r.shape[0]) * 0.6
plt.bar(df.index, df['Mean'], yerr=df['yerr'], capsize=7,
        color=list(zip(r, g, b, a)))

plt.show()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM