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

Tạo biểu đồ radar (spider) đa giác trong Python Matplotlib


Để tạo biểu đồ radar (spider) đa giác trong Python, thực hiện các bước sau:

Các bước

  • Thiết lập kích thước hình và padding.
  • Tạo DataFrame Pandas cột sports và values.
  • Tạo figure mới.
  • Thêm axes polar projection.
  • Tính theta từ số lượng hàng DataFrame.
  • Lấy danh sách values, thêm giá trị đầu vào cuối để khép kín.
  • Vẽ đường polar plot với theta, values.
  • Tô màu vùng trong đa giác.
  • Hiển thị hình bằng show().

Ví dụ

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'sports': ['Strength', 'Speed', 'Power', 'Agility', 'Endurance', 'Analytical Aptitude'],
                   'values': [7, 8, 6, 10, 8, 9]})
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")
theta = np.arange(len(df) + 1) / float(len(df)) * 2 * np.pi
values = df['values'].values
values = np.append(values, values[0])
l1, = ax.plot(theta, values, color="purple", marker="o", label="Name of values")
ax.tick_params(pad=10)
ax.fill(theta, values, 'green', alpha=0.3)
plt.show()

Kết quả

Biểu đồ radar (spider chart) 6 trục, đường viền tím, marker tròn, vùng tô xanh lá trong suốt.