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

Vẽ dữ liệu từ file .txt bằng matplotlib

Để vẽ dữ liệu từ file .txt bằng matplotlib, thực hiện các bước sau:

  • Đặt kích thước hình và điều chỉnh padding giữa và xung quanh subplots.
  • Khởi tạo danh sách rỗng cho bar_names và bar_heights.
  • Mở file .txt mẫu ở chế độ đọc "r" và thêm vào danh sách tên và chiều cao cột.
  • Tạo biểu đồ cột.
  • Để hiển thị hình, dùng show().

Ví dụ

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
bar_names = []
bar_heights = []
for line in open("test_data.txt", "r"):
    bar_name, bar_height = line.split()
    bar_names.append(bar_name)
    bar_heights.append(bar_height)
plt.bar(bar_names, bar_heights)
plt.show()

File "test_data.txt" chứa dữ liệu sau:

Javed 12
Raju  14
Rishi 15
Kiran 10
Satish 17
Arun 23

Kết quả

Sẽ tạo ra đầu ra sau:

Vẽ dữ liệu từ file .txt bằng matplotlibVẽ dữ liệu từ file .txt bằng matplotlib