Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách vẽ nhiều biểu đồ trên một trang bằng matplotlib trong Python


Sử dụng Pandas, tạo dataframe và figure, axes. Sau đó dùng scatter để vẽ điểm.

Các bước

  • Tạo list học sinh, điểm, color coding.

  • Tạo dataframe bằng DataFrame pandas với dữ liệu bước 1.

  • Tạo fig, ax bằng subplots(), mặc định nrows=ncols=1.

  • Đặt nhãn trục X bằng plt.xlabel().

  • Đặt nhãn trục Y bằng plt.ylabel().

  • Vẽ scatter plot y vs x với marker size/color thay đổi.

  • Hiển thị figure bằng plt.show().

Ví dụ

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('Students count')
plt.ylabel('Obtained marks')
ax.scatter(df['students_count'], df['marks'], c=df['color'])
plt.show()

Kết quả

Cách vẽ nhiều biểu đồ trên một trang bằng matplotlib trong Python