条件下的Pandas/Matplotlib条形图颜色

4
我正在尝试使用pandas/matplotlib制作学生作业问题的条形图。我可以轻松制作条形图,但我想根据学生的分数选择颜色。例如,我希望可以将得分<=50的设置为红色,将得分>50且<=75的设置为黄色等等。
以下是我目前的代码:
import pandas as pd
import matplotlib.pyplot as plt
# make some arrays
score = [100, 50, 43, 67, 89, 2, 13, 56, 22, -1, 53]
homework_problem = ['A', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'C', 'D', 'B']
topic = ['F', 'G', 'H', 'G', 'H', 'F', 'H', 'G', 'G', 'F', 'H']

# put the arrays into a pandas df
df = pd.DataFrame()
df['score'] = score
df['homework_problem'] = homework_problem
df['topic'] = topic

#make sure it looks okay
print(df)

# let's groupby and plot
df.groupby(['homework_problem','score'])['topic'].size().unstack().plot(kind='bar',stacked=True, title = "Test")
plt.show()

以下是输出下面的图表的代码: 上述代码输出的图表。

1个回答

5
您可以尝试这样做:
# make some arrays
score = [100, 50, 43, 67, 89, 2, 13, 56, 22, -1, 53]
homework_problem = ['A', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'C', 'D', 'B']
topic = ['F', 'G', 'H', 'G', 'H', 'F', 'H', 'G', 'G', 'F', 'H']

# put the arrays into a pandas df
df = pd.DataFrame()
df['score'] = score
df['homework_problem'] = homework_problem
df['topic'] = topic

df['scoregroup'] = pd.cut(df['score'],bins=[0,50,75,100], labels=['Poor','Bad','Good'])

#make sure it looks okay
print(df)

# let's groupby and plot
d = df.groupby(['homework_problem','scoregroup'])['topic'].size().unstack()
d.plot(kind='bar',stacked=True, title = "Test")

输出:

    score homework_problem topic scoregroup
0     100                A     F       Good
1      50                B     G       Poor
2      43                C     H       Poor
3      67                B     G        Bad
4      89                A     H       Good
5       2                D     F       Poor
6      13                D     H       Poor
7      56                A     G        Bad
8      22                C     G       Poor
9      -1                D     F        NaN
10     53                B     H        Bad

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接