简体   繁体   English

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

[英]Pandas/Matplotlib bar chart color by condition

I am trying to make a bar chart of student scores by homework problem using pandas/matplotlib. 我正在尝试使用pandas / matplotlib通过作业问题制作学生成绩的条形图。 I can make the bar chart no problem, but what I would like to do is select the color by the student score. 我可以使条形图没问题,但是我想做的就是根据学生的分数选择颜色。 For example, I am hoping that I can make scores <= 50 red, scores > 50 and <=75 yellow, etc. 例如,我希望我可以使得分<= 50红色,得分> 50和<= 75黄色等等。

Here is a where I'm currently at 这是我目前在的地方

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

which outputs the plot below 输出下面的图 图由以上代码输出。

You can try this: 您可以尝试以下方法:

# 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")

Output: 输出:

    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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM