熊猫/ Matplotlib条形图按条件划分的颜色

时间:2019-01-17 16:58:47

标签: python pandas matplotlib pandas-groupby

我正在尝试使用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()

输出下面的图 Figure output by the above code.

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

# 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