数学建模--Radar图绘制

news2024/9/30 13:25:49

1.Radar图简介

   最近在数学建模中碰见需要绘制Radar图(雷达图)的情况来具体分析样本的各个特征之间的得分与优劣关系,这样的情况比较符合雷达图的使用场景,一般来说,雷达图适用于展示多个维度的数据,并在一个平面上直观地呈现出不同维度的变化趋势,比较适用的场合如下:

    ∙ \bullet 综合评价: 雷达图是理想的工具,能够直观展示多个评价指标的得分,为综合评估提供清晰的整体表现概览。

    ∙ \bullet SWOT分析: 通过SWOT分析,雷达图展示了组织或项目在各方面的优势、劣势、机会和威胁,为战略决策提供直观支持。

    ∙ \bullet 个体特征对比: 通过雷达图,我们可以比较不同个体在各个特征上的差异,无论是个人技能评估还是产品性能对比,一目了然。

2.Radar图绘图案例:单样本图绘制

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import warnings
warnings.filterwarnings("ignore")
matplotlib.rcParams['font.family'] = 'serif'
matplotlib.rcParams['font.serif'] = 'Times New Roman'
#需要评价的特征名称
labels = np.array(['Comprehensive', 'Education', 'Professional Title', 'Teaching', 'Training', 'Research'])
labels = np.array(['A1', 'A2', 'A3', 'A4', 'A5', 'A6'])
#需要评价的特征的数量
nAttr = len(labels)
#数据/得分情况
data = np.array([8, 5, 8, 9, 8, 6])
#计算角度360/n
angels = np.linspace(0, 2*np.pi, nAttr, endpoint=False)
#创建数据闭环效果
data = np.concatenate((data, [data[0]]))  
angels = np.concatenate((angels, [angels[0]]))


#可视化绘图
fig = plt.figure(facecolor='white')
ax = plt.subplot(111, polar=True)

ax.set_ylim(0, 10)
#绘制线条
ax.plot(angels, data, 'o-', color='lightgreen', linewidth=2, label='A Personal Characteristics')

#添加数值标签(选写)
for i in range(len(angels)-1):
    ax.text(angels[i], data[i]+0.8, str(data[i]), color='b')

#填充区域
ax.fill(angels, data, facecolor='red', alpha=0.25)
ax.set_xticks(angels[:-1])
ax.set_xticklabels(labels, ha='center')
ax.set_title('Academic Scholar Research Feature Radar Chart', va='bottom', fontweight='bold')
#设置一些图例要求
plt.grid(True)
#plt.legend(loc='upper right')
#plt.legend(loc='upper right', bbox_to_anchor=(1.2, 0.55), bbox_transform=plt.gcf().transFigure)
plt.savefig('雷达图1.jpg')
plt.show()

在这里插入图片描述

3.Radar图绘图案例:多样本图绘制

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import warnings

warnings.filterwarnings("ignore")

matplotlib.rcParams['font.family'] = 'serif'
matplotlib.rcParams['font.serif'] = 'Times New Roman'
matplotlib.rcParams['font.style'] = 'italic' 

radar_labels = np.array(['A1', 'A2', 'A3',
                         'A4', 'A5', 'A6'])
nAttr = 6

data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
                 [0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
                 [0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
                 [0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
                 [0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
                 [0.34, 0.31, 0.38, 0.40, 0.92, 0.28]])
data_labels = ('Engineer', 'Laboratory Technician', 'Artist', 'Salesperson', 'Social Worker', 'Clerk')

angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False)

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

fig = plt.figure(facecolor='white')
ax = plt.subplot(111, polar=True)

ax.plot(angles, data, 'o-', linewidth=1, alpha=0.2)
ax.fill(angles, data, alpha=0.3)

ax.set_thetagrids(np.degrees(angles[0:6]), labels=radar_labels)
ax.set_title('Holland Personality Analysis', va='bottom', fontweight='bold', size=16)

legend = plt.legend(data_labels, loc=(1.1, 0.55), labelspacing=0.1, edgecolor='k', fontsize=10)

plt.grid(True)
plt.savefig('雷达图2.jpg')
plt.show()

在这里插入图片描述

4.Radar图绘图案例:Matplotlib标准绘图案例

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D


def radar_factory(num_vars, frame='circle'):
    """
    Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle', 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarTransform(PolarAxes.PolarTransform):

        def transform_path_non_affine(self, path):
            # Paths with non-unit interpolation steps correspond to gridlines,
            # in which case we force interpolation (to defeat PolarTransform's
            # autoconversion to circular arcs).
            if path._interpolation_steps > 1:
                path = path.interpolated(num_vars)
            return Path(self.transform(path.vertices), path.codes)

    class RadarAxes(PolarAxes):

        name = 'radar'
        PolarTransform = RadarTransform

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.append(x, x[0])
                y = np.append(y, y[0])
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars,
                                      radius=.5, edgecolor="k")
            else:
                raise ValueError("Unknown value for 'frame': %s" % frame)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)
                return {'polar': spine}
            else:
                raise ValueError("Unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta


def example_data():
    # The following data is from the Denver Aerosol Sources and Health study.
    # See doi:10.1016/j.atmosenv.2008.12.017
    #
    # The data are pollution source profile estimates for five modeled
    # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical
    # species. The radar charts are experimented with here to see if we can
    # nicely visualize how the modeled source profiles change across four
    # scenarios:
    #  1) No gas-phase species present, just seven particulate counts on
    #     Sulfate
    #     Nitrate
    #     Elemental Carbon (EC)
    #     Organic Carbon fraction 1 (OC)
    #     Organic Carbon fraction 2 (OC2)
    #     Organic Carbon fraction 3 (OC3)
    #     Pyrolyzed Organic Carbon (OP)
    #  2)Inclusion of gas-phase specie carbon monoxide (CO)
    #  3)Inclusion of gas-phase specie ozone (O3).
    #  4)Inclusion of both gas-phase species is present...
    data = [
        ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
        ('Basecase', [
            [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
            [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
            [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
            [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
            [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),
        ('With CO', [
            [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],
            [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],
            [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],
            [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],
            [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),
        ('With O3', [
            [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],
            [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],
            [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],
            [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],
            [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),
        ('CO & O3', [
            [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],
            [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],
            [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],
            [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],
            [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])
    ]
    return data


if __name__ == '__main__':
    N = 9
    theta = radar_factory(N, frame='polygon')

    data = example_data()
    spoke_labels = data.pop(0)

    fig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,
                            subplot_kw=dict(projection='radar'))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

    colors = ['b', 'r', 'g', 'm', 'y']
    # Plot the four cases from the example data on separate axes
    for ax, (title, case_data) in zip(axs.flat, data):
        ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
                     horizontalalignment='center', verticalalignment='center')
        for d, color in zip(case_data, colors):
            ax.plot(theta, d, color=color)
            ax.fill(theta, d, facecolor=color, alpha=0.25, label='_nolegend_')
        ax.set_varlabels(spoke_labels)

    # add legend relative to top-left plot
    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
    legend = axs[0, 0].legend(labels, loc=(0.98, -0.2),
                              labelspacing=0.1, fontsize=12,edgecolor='k')

    fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
             horizontalalignment='center', color='black', weight='bold',
             size=16)
    plt.savefig('雷达图3.jpg')  
    plt.show()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1402908.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

宠物空气净化器推荐哪个好?实惠的猫用猫用净化器牌子测评

作为宠物主人,我们深知养宠物的乐趣和责任,但同时也面临着一些挑战,比如宠物掉毛、异味和空气质量等问题。这就是为什么越来越多的家庭选择宠物空气净化器,为我们创造一个清新、健康的室内环境。 无论我们多么爱我们的毛茸茸伙伴…

如何在 Ubuntu 22.04 上安装 Apache Web 服务器

前些天发现了一个人工智能学习网站,通俗易懂,风趣幽默,最重要的屌图甚多,忍不住分享一下给大家。点击跳转到网站。 如何在 Ubuntu 22.04 上安装 Apache Web 服务器 介绍 Apache HTTP 服务器是世界上使用最广泛的 Web 服务器。它…

【C++】priority_queue模拟实现过程中值得注意的点

👀樊梓慕:个人主页 🎥个人专栏:《C语言》《数据结构》《蓝桥杯试题》《LeetCode刷题笔记》《实训项目》《C》《Linux》《算法》 🌝每一个不曾起舞的日子,都是对生命的辜负 前言 本篇文章旨在记录博主在模…

[已解决]mysql关闭SSL功能和永久关闭SSL设置

概述 在搭建服务器连接本地数据库时发现有个报错信息: SQLState - 08S01 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 292 milliseconds ago. The last …

如何查看苹果手机的CPU型号?

摘要 本文将介绍如何在苹果手机上查看CPU型号。通过简单的设置操作,您可以轻松地获取您的iPhone的CPU型号信息。此外,我们还将介绍一些克魔助手可以提供的其他功能,如内存监控、GPU性能监控和网络抓包等,以帮助您优化和提升iOS应…

设计模式—行为型模式之观察者模式

设计模式—行为型模式之观察者模式 观察者模式(Observer Pattern):定义对象间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。观察者模式又叫做发布-订阅(Publish/Subscribe&#…

三.Winform使用Webview2加载本地HTML页面

Winform使用Webview2加载本地HTML页面 往期目录创建Demo2界面创建HTML页面在Demo2窗体上添加WebView2和按钮加载HTML查看效果 往期目录 往期相关文章目录 专栏目录 创建Demo2界面 经过前面两小节 一.Winform使用Webview2(Edge浏览器核心) 创建demo(Demo1)实现回车导航到指定…

同星多通道CAN FD转USB/WIFI设备,解决近距离无线通讯问题

新品发布/New products release 2024年1月,同星智能连续发布FlexRay系列产品TP1034和以太网系列产品TP1051,上周发布多通道总线记录仪产品TLog1004。1月19日,同星智能又推出一款2/4路CAN FD转USB和WIFI的工具,解决近距离无线通讯…

L1-079 天梯赛的善良(Java)

天梯赛是个善良的比赛。善良的命题组希望将题目难度控制在一个范围内,使得每个参赛的学生都有能做出来的题目,并且最厉害的学生也要非常努力才有可能得到高分。 于是命题组首先将编程能力划分成了 106 个等级(太疯狂了,这是假的&…

如何使用支付宝沙箱环境本地配置模拟支付并结合内网穿透远程调试

文章目录 前言1. 下载当面付demo2. 修改配置文件3. 打包成web服务4. 局域网测试5. 内网穿透6. 测试公网访问7. 配置二级子域名8. 测试使用固定二级子域名访问 正文开始前给大家推荐个网站,前些天发现了一个巨牛的 人工智能学习网站, 通俗易懂&#xff…

基于光口的以太网 udp 回环实验

文章目录 前言一、系统框架整体设计二、系统工程及 IP 创建三、UDP回环模块修改说明四、接口讲解五、顶层模块设计六、下载验证前言 本章实验我们通过网络调试助手发送数据给 FPGA,FPGA通过光口接收数据并将数据使用 UDP 协议发送给电脑。 提示:任何文章不要过度深思!万事万…

【SpringBoot技术专题】「开发实战系列」Undertow web容器的入门实战及调优方案精讲

Undertow web容器的入门实战及调优方案精讲 Undertow web容器Undertow 介绍官网API给出一句话概述Undertow:官网API总结特点:Lightweight(轻量级)HTTP Upgrade Support(支持http升级)、HTTP/2 Support支持H…

浅谈linux中的根文件系统(rootfs的原理和介绍)【转】

浅谈linux中的根文件系统(rootfs的原理和介绍)【转】 转自:https://www.cnblogs.com/sky-heaven/p/13742173.html linux中有一个让不少初学者都不是特别清楚的概念,叫作“根文件系统”。我接触linux前先后后也好几年了&#xff0…

Hystrix-熔断机制

1.1. 雪崩效应 熔断发生在服务端,降级发生在客户端; 分布式系统环境下,服务间类似依赖非常常见,一个业务调用通常依赖多个基础服务。如下图,对于同步调用,当库存服务不可用时,商品服务请求线程…

使用pysimplegui+opencv编写一个摄像头的播放器

需求 使用pysimplegui和opencv实现一个播放器,播放 摄像头的画面。 代码实现 import cv2 import time from typing import Iterable, NamedTuple, Optionalimport PySimpleGUI as sgclass CameraSpec(NamedTuple):name: strindex: intwidth: intheight: intfps: i…

【英文干货】【Word_Search】找单词游戏(第1天)

本期主题:Mindfulness(意识力) 本期单词: Awareness 意识 Breathing 呼吸 Calm 平静的 De-Stress 减压 Feelings 感受,情感 Inspection 调查 Meditation 冥想 Peace 和平 Quiet 安静的 Recollection 回忆 R…

深入理解java对象的内存布局

概述: 在HotSpot虚拟机里,对象在堆内存中的存储布局可以划分为三个部分:对象头(Header)、实例数据(Instance Data)和对齐填充(Padding)。 在HotSpot虚拟机里,…

网络安全全栈培训笔记(57-服务攻防-应用协议RsyncSSHRDPFTP漏洞批量扫描口令拆解)

第57天 服务攻防-应用协议&Rsync&SSH&RDP&FTP&漏洞批量扫描&口令拆解 知识点: 1、服务攻防-远程控制&文件传输等 2、远程控制-RDP&RDP&弱口令&漏洞 3、文件传输-FTP&Rsyc&弱口令&漏洞 章节内容:…

vmware 安装Rocky-9.3系统

安装系统截图 安装完成,启动 查看版本和内核 开启远程登陆授权 1、编辑配置文件 #提升权限,输入su,并输入密码 su #编辑ssh文件开启root远程登陆 vi /etc/ssh/sshd_config找到以下内容:#PermitRootLogin prohibit-password 添加&#xff1a…

13个常见的 WordPress 块编辑器问题以及如何修复它们

您在使用 WordPress 块编辑器时遇到过错误吗? WordPress 在 2019 年用名为 Gutenberg 的全新内容编辑器取代了旧的经典编辑器。该编辑器使用块在 WordPress 中创建内容。然而,有时,在使用它时可能会遇到恼人的问题。 在本文中,我…