错误:如果条件为True,则更改条形图的颜色matplotlib

2024-10-01 07:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有正数和负数的数据框作为条形图。 如何绘制正值的“橙色”​​“天蓝色”表示负值

颜色未更改时的代码为:

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)

enter image description here

我试图改变颜色:

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 argumentThisThis)和how to change the colorThisThis)相关的帖子,但它们不起作用。
有人能帮忙吗


Tags: theimportdfmatplotlibvalueasrangeplt
1条回答
网友
1楼 · 发布于 2024-10-01 07:34:39

您可以将数据框拆分为正值和负值,并分别绘制它们:

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')

# Separate the dataframe into positive and negative values
df_pos = df[(df>0)]
df_neg= df[(df<0)]

my_range_pos=list(range(1,len(df_pos.index)+1))
my_range_neg=list(range(1,len(df_neg.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.
# Plot positive
plt.hlines(y=my_range_pos, xmin=0, xmax=df_pos['Value'], color='orange', alpha=0.2, linewidth=5)
# Plot negative
plt.hlines(y=my_range_neg, xmin=0, xmax=df_neg['Value'], color='blue', alpha=0.2, linewidth=5)

# create for each expense type a dot at the level of the expense percentage value
# Plot positive
plt.plot(df_pos['Value'], my_range_pos, "o", markersize=5, color='orange', alpha=0.6)
# Plot negative
plt.plot(df_neg['Value'], my_range_neg, "o", markersize=5, color='blue', alpha=0.6)

结果:

enter image description here

相关问题 更多 >