使用Python的pandas从数据框创建matplotlib散点图
使用Pandas,我们可以创建一个数据框,并使用subplot()方法创建一个图形和轴变量。然后,我们可以使用ax.scatter()方法获取所需的绘图。
步骤
- 制作一个学生数量列表。
-
制作学生所获得的分数列表。
-
为每个散点表示的颜色,我们可以使用颜色列表。
-
使用Pandas,我们可以有一个表示数据框轴的列表。
-
使用subplots方法创建fig和ax变量,其中默认的nrows和ncols为1。
-
使用plt.xlabel()方法设置“学生数量”标签。
-
使用plt.ylabel()方法设置“获得分数”标签。
-
使用在步骤4中创建的数据框创建散点图。点是students_count,marks和color。
-
使用plt.show()方法显示图形。
示例
from matplotlib import pyplot as plt
import pandas as pd
no_of_students = [1, 2, 3, 5, 7, 8, 9, 10, 30, 50]
marks_obtained_by_student = [100, 95, 91, 90, 89, 76, 55, 10, 3, 19]
color_coding = ['red', 'blue', 'yellow', 'green', 'red', 'blue', 'yellow', 'green', 'yellow', 'green']
df = pd.DataFrame(dict(students_count=no_of_students,
marks=marks_obtained_by_student, color=color_coding))
fig, ax = plt.subplots()
plt.xlabel('学生数量')
plt.ylabel('获得分数')
ax.scatter(df['students_count'], df['marks'], c=df['color'])
plt.show()