python雷达图的相似度_具有轴尺度变化的Python Matplolib多雷达图

如何将这两种方法合并到同一个程序中?在

一方面,matplotlib中的this code用于创建雷达图。在

另一方面,this code允许您更改每个轴的比例,甚至可以向其添加负数。在

我要找的合并是能够像matplotlib方法一样绘制大量不同的数据,但是能够在其中的每一个绘图中进行更改,即轴比例。在

编辑:代码已尝试import numpy as np

import matplotlib.pyplot as plt

# import seaborn as sns # improves plot aesthetics

def _invert(x, limits):

"""inverts a value x on a scale from

limits[0] to limits[1]"""

return limits[1] - (x - limits[0])

def _scale_data(data, ranges):

"""scales data[1:] to ranges[0],

inverts if the scale is reversed"""

# for d, (y1, y2) in zip(data[1:], ranges[1:]):

for d, (y1, y2) in zip(data, ranges):

assert (y1 <= d <= y2) or (y2 <= d <= y1)

x1, x2 = ranges[0]

d = data[0]

if x1 > x2:

d = _invert(d, (x1, x2))

x1, x2 = x2, x1

sdata = [d]

for d, (y1, y2) in zip(data[1:], ranges[1:]):

if y1 > y2:

d = _invert(d, (y1, y2))

y1, y2 = y2, y1

sdata.append((d-y1) / (y2-y1) * (x2 - x1) + x1)

return sdata

def set_rgrids(self, radii, labels=None, angle=None, fmt=None,

**kwargs):

"""

Set the radial locations and labels of the *r* grids.

The labels will appear at radial distances *radii* at the

given *angle* in degrees.

*labels*, if not None, is a ``len(radii)`` list of strings of the

labels to use at each radius.

If *labels* is None, the built-in formatter will be used.

Return value is a list of tuples (*line*, *label*), where

*line* is :class:`~matplotlib.lines.Line2D` instances and the

*label* is :class:`~matplotlib.text.Text` instances.

kwargs are optional text properties for the labels:

%(Text)s

ACCEPTS: sequence of floats

"""

# Make sure we take into account unitized data

radii = self.convert_xunits(radii)

radii = np.asarray(radii)

rmin = radii.min()

# if rmin <= 0:

# raise ValueError('radial grids must be strictly positive')

self.set_yticks(radii)

if labels is not None:

self.set_yticklabels(labels)

elif fmt is not None:

self.yaxis.set_major_formatter(FormatStrFormatter(fmt))

if angle is None:

angle = self.get_rlabel_position()

self.set_rlabel_position(angle)

for t in self.yaxis.get_ticklabels():

t.update(kwargs)

return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()

class ComplexRadar():

def __init__(self, fig, variables, ranges,

n_ordinate_levels=6):

angles = np.arange(0, 360, 360./len(variables))

axes = [fig.add_axes([0.1,0.1,0.9,0.9],polar=True,

label = "axes{}".format(i))

for i in range(len(variables))]

l, text = axes[0].set_thetagrids(angles,

labels=variables)

[txt.set_rotation(angle-90) for txt, angle

in zip(text, angles)]

for ax in axes[1:]:

ax.patch.set_visible(False)

ax.grid("off")

ax.xaxis.set_visible(False)

for i, ax in enumerate(axes):

grid = np.linspace(*ranges[i],

num=n_ordinate_levels)

gridlabel = ["{}".format(round(x,2))

for x in grid]

if ranges[i][0] > ranges[i][1]:

grid = grid[::-1] # hack to invert grid

# gridlabels aren't reversed

gridlabel[0] = "" # clean up origin

# ax.set_rgrids(grid, labels=gridlabel, angle=angles[i])

set_rgrids(ax, grid, labels=gridlabel, angle=angles[i])

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

ax.set_ylim(*ranges[i])

# variables for plotting

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

self.ranges = ranges

self.ax = axes[0]

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

sdata = _scale_data(data, self.ranges)

self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)

def fill(self, data, *args, **kw):

sdata = _scale_data(data, self.ranges)

self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)

# example data

variables = ('ST-1', 'ST-2', 'ST-3', 'ST-4', 'ST-5', 'ST-6', 'ST-7', 'ST-16', 'SC-1', 'SC-2')

data = (34.0, 32.1, 28.6, 28.6, 28.9, 28.3, 26.3, 39.6, 3.2, 1.3)

ranges = [(20, 40), (20, 40),(20, 40),(20, 40),(20, 40),(20, 40),(20, 40),(20, 40),(0, 5), (0, 5)]

# plotting

fig1 = plt.figure(figsize=(9, 9))

radar = ComplexRadar(fig1, variables, ranges)

radar.plot(data, label='Test 1')

radar.fill(data, alpha=0.2)

data = (20.0, 23.4, 22.7, 21.3, 26.9, 26.2, 21.3, 22.3, 3.7, 1.0)

radar = ComplexRadar(fig1, variables, ranges)

radar.plot(data, label='Test 2')

radar.fill(data, alpha=0.2)

data = (38.0, 30.1, 25.6, 22.6, 29.9, 38.3, 28.3, 24.6, 3.0, 1.8)

radar = ComplexRadar(fig1, variables, ranges)

radar.plot(data, label='Test 3')

radar.fill(data, alpha=0.2)

labels = ('Test 1', 'Test 2', 'Test 3')

legend = radar.legend(labels, loc=(0.9, .95), labelspacing=0.1, fontsize='small')

plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
雷达图(Radar Chart),也称为蜘蛛网图(Spider Chart)或星形图(Star Chart),是一种多变量数据可视化方式,通常用于比较多个变量或维度的相对关系。 Python使用`matplotlib`库可以绘制雷达图。下面我将为你详细讲解如何使用Python绘制雷达图。 首先,我们需要导入相关的库: ```python import numpy as np import matplotlib.pyplot as plt ``` 接下来,我们需要准备数据。假设我们要绘制一个学生的五项能力评估雷达图,其包括语文、数学、英语、体育和艺术五个维度的得分: ```python labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) ``` 然后,我们需要计算出每个维度在雷达图的角度。因为雷达图是一个圆形,所以每个维度的角度应该是均分360度,即每个角度应该是`360 / 数据维度个数`。代码如下: ```python angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) ``` 接下来,我们需要将数据和角度转换成极坐标系下的坐标。这里我们可以使用`np.vstack()`函数将数据和第一个数据点组合起来,再使用`np.cos()`和`np.sin()`函数计算出每个数据点的坐标。代码如下: ```python data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) ``` 最后,我们可以使用`matplotlib`的`plot()`函数绘制出雷达图代码如下: ```python fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) ``` 完整的代码如下: ```python import numpy as np import matplotlib.pyplot as plt labels = np.array(['语文', '数学', '英语', '体育', '艺术']) data = np.array([90, 80, 85, 70, 60]) angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False) angles = np.concatenate((angles, [angles[0]])) data = np.concatenate((data, [data[0]])) coords = np.vstack((angles, data)).T coords = np.concatenate((coords, [coords[0]])) fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True)) ax.plot(angles, data, 'o-', linewidth=2) ax.fill(coords[:, 0], coords[:, 1], alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title('学生五项能力评估') ax.grid(True) plt.show() ``` 运行代码,我们可以看到绘制出来的雷达图: ![雷达图](https://img-blog.csdnimg.cn/20211104121534521.png) 这个雷达图表示该学生在语文、数学、英语、体育和艺术五个维度上的得分情况,可以用于对比不同学生在这五个维度上的能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值