Python matplotlib用绘制雷达图实战案例

Python021

Python matplotlib用绘制雷达图实战案例,第1张

import pandasas pd

import matplotlib.pyplotas plt

import numpyas np

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

plt.rcParams['axes.unicode_minus'] =False

data = pd.read_csv(r'D:\bigData\radarMap.csv')

data = data.dropna(axis=1)

data = data.set_index('性能评价指标')

data = data.T

data.index.name ='品牌'

def plot_radar(data, feature):

columns = ['动力性', '燃油经济性', '制动性', '操控稳定性', '行驶平顺性', '通过性', '安全性', '环保性', '方便性', '舒适性', '经济性', '容量性']

colors = ['r', 'g', 'y']

# 设置雷达图的角度,用于平分切开一个平面

    # linspace(1,10,x) 创建1-10的等差数组,个数为 x,默认50个endpoint参数指定是否包含终值,默认值为True,即包含终值。

    angles = np.linspace(0.1 * np.pi, 2.1 * np.pi, len(columns), endpoint=False)

# 使雷达图封闭起来

    angles = np.concatenate((angles, [angles[0]]))

# figsize:指定figure的宽和高,单位为英寸;

    figure = plt.figure(figsize=(6, 6))

# 设置为极坐标格式subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)创建单个子图,下面两句效果相同

    ax = figure.add_subplot(111, polar=True)

for i, cin enumerate(feature):

stats = data.loc[c]

stats = np.concatenate((stats, [stats[0]]))

ax.plot(angles, stats, '-', linewidth=2, c=colors[i], label=str(c))

ax.fill(angles, stats, color=colors[i], alpha=0.75)

# bbox_to_anchor这个参数,可以把图例放在图外面

    # bbox_to_anchor:表示legend的位置,前一个表示左右,后一个表示上下。

    # 当使用这个参数时。loc将不再起正常的作用,ncol=3表示图例三列显示。

    ax.legend(loc=4, bbox_to_anchor=(1.15, -0.07))

# 设置极轴范围

    ax.set_ylim(0, 10)

# ax.set_yticklabels([2, 4, 6, 8, 10])

    # 添加每个特质的标签

    columns = np.concatenate((columns, [columns[0]]))

ax.set_thetagrids(angles *180 / np.pi, columns, fontsize=12)

# 添加标题

    plt.title('汽车性能指标雷达图')

plt.show()

return figure

figure = plot_radar(data, ['A品牌', 'B品牌', 'C品牌'])

import numpy as np

import pylab as pl

class Radar(object):

  def __init__(self, fig, titles, labels, rect=None):

      if rect is None:

          rect = [0.05, 0.05, 0.95, 0.95]

      self.n = len(titles)

      self.angles = np.arange(90, 90+360, 360.0/self.n)

      self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i)

                       for i in range(self.n)]

      self.ax = self.axes[0]

      self.ax.set_thetagrids(angles, labels=titles, fontsize=14)

      for ax in self.axes[1:]:

          ax.patch.set_visible(False)

          ax.grid("off")

          ax.xaxis.set_visible(False)

      for ax, angle, label in zip(self.axes, self.angles, labels):

          ax.set_rgrids(range(1, 6), angle=angle, labels=label)

          ax.spines["polar"].set_visible(False)

          ax.set_ylim(0, 5)

  def plot(self, values, *args, **kw):

      angle = np.deg2rad(np.r_[self.angles, self.angles[0]])

      values = np.r_[values, values[0]]

      self.ax.plot(angle, values, *args, **kw)

titles = list("ABCDE")

labels = [

  list("abcde"), list("12345"), list("uvwxy"),

  ["one", "two", "three", "four", "five"],

  list("jklmn")

]

fig = pl.figure(figsize=(6, 6))

titles = list("ABCDE")

labels = [

  list("abcde"), list("12345"), list("uvwxy"),

  ["one", "two", "three", "four", "five"],

  list("jklmn")

]

radar = Radar(fig, titles, labels)

radar.plot([1, 3, 2, 5, 4],  "-", lw=2, color="b", alpha=0.4, label="first")

radar.plot([2.3, 2, 3, 3, 2],"-", lw=2, color="r", alpha=0.4, label="second")

radar.plot([3, 4, 3, 4, 2], "-", lw=2, color="g", alpha=0.4, label="third")

radar.ax.legend()