Pandas/Matplotlib条形图颜色(按条件)

2024-05-17 18:57:58 发布

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

我试着用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.


Tags: importltpandasdftopicmatplotlibasplt
1条回答
网友
1楼 · 发布于 2024-05-17 18:57:58

你可以试试这个:

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

输出:

^{pr2}$

enter image description here

相关问题 更多 >