Python 如何根据数据帧(pandas)中的值设置条形图(matplotlib)的颜色?
我想从数据帧创建条形图。但是我想根据数据框中“red”列的值给每个条上色。 我有以下代码:Python 如何根据数据帧(pandas)中的值设置条形图(matplotlib)的颜色?,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想从数据帧创建条形图。但是我想根据数据框中“red”列的值给每个条上色。 我有以下代码: 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.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()
请提供一些样本数据和预期输出,非常感谢!成功了!你能解释一下为什么这样做吗?@carloslivares如果你看一下,你会发现它需要一个定标器(所以所有的条都是相同的颜色)或者一个类似数组的对象。“类似数组”实际上是指一个二维数组,其中每行是一个单独的(r,g,b,a)参数,每列对应一个数据点。我同意,这不是很明显。我所知道的关于matplotlib的大部分知识都是通过反复试验学到的。不客气,祝你好运!哎呀!我的意思是说每一行都是(r,g,b,a),并且应该有和数据点一样多的行。