【发布时间】:2020-10-27 09:58:44
【问题描述】:
我有一个带有正负值的 pandas DataFrame 作为条形图。 如何为正值绘制“橙色”,为负值绘制“天蓝色”?
不改变颜色时的代码是:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
%matplotlib inline
# create some fake data
Value = pd.Series([-20, -15, 18, -8, 6, 7, 10, 2, 10, 4],
index=['Rent', 'Transportation', 'Bills', 'Food',
'Travel', 'Entertainment', 'Health', 'Other', 'Clothes', 'Phone'])
df = pd.DataFrame({'Value' : Value})
df = df.sort_values(by='Value')
my_range=list(range(1,len(df.index)+1))
fig, ax = plt.subplots(figsize=(5,3.5))
#color
clrs='orange'
# create for each expense type an horizontal line that starts at x = 0 with the length
# represented by the specific expense percentage value.
plt.hlines(y=my_range, xmin=0, xmax=df['Value'], color=clrs, alpha=0.2, linewidth=5)
# create for each expense type a dot at the level of the expense percentage value
plt.plot(df['Value'], my_range, "o", markersize=5, color=clrs, alpha=0.6)
我尝试改变颜色:
clrs = np.where(df['percentage']>0, 'orange', 'skyblue')
但是我得到了:
ValueError: Invalid RGBA argument: array(['skyblue', 'skyblue', 'skyblue', 'orange', 'orange', 'orange',
'orange', 'orange', 'orange', 'orange'], dtype='<U7')
我查看了与Invalid RGBA argument(This, This) 和how to change the color(This, This) 相关的帖子,但它们不起作用。
有人可以帮忙吗?
【问题讨论】:
标签: python dataframe matplotlib colors