Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >matplotlib 雷达图/蛛网图

matplotlib 雷达图/蛛网图

作者头像
用户6021899
发布于 2019-08-14 08:47:10
发布于 2019-08-14 08:47:10
2.2K00
代码可运行
举报
运行总次数:0
代码可运行

本篇讲解如何用matplotlib 画雷达图(蛛网图)。

第一个例子来自matplotlib官网,封装比较多,看起来有点复杂,但本质上是在极坐标系下画封闭的曲线图。

代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
"""
======================================
Radar chart (aka spider or star chart)
======================================
This example creates a radar chart, also known as a spider or star chart [1]_.
Although this example allows a frame of either 'circle' or 'polygon', polygon
frames don't have proper gridlines (the lines are circles instead of polygons).
It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in
matplotlib.axis to the desired number of vertices, but the orientation of the
polygon is not aligned with the radial axes.
.. [1] http://en.wikipedia.org/wiki/Radar_chart
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection

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)#角度(弧度制)
    def draw_poly_patch(self):
        # rotate theta such that the first axis is at the top
        verts = unit_poly_verts(theta + np.pi / 2)
        return plt.Polygon(verts, closed=True, edgecolor='k')
    def draw_circle_patch(self):
        # unit circle centered on (0.5, 0.5)
        return plt.Circle((0.5, 0.5), 0.5) #画圆
    patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}
    if frame not in patch_dict:
        raise ValueError('unknown value for `frame`: %s' % frame)
    class RadarAxes(PolarAxes):
        name = 'radar'
        # use 1 line segment to connect specified points
        RESOLUTION = 1
        # define draw_frame method
        draw_patch = patch_dict[frame]
        def __init__(self, *args, **kwargs):
            super(RadarAxes, self).__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')
        def fill(self, *args, **kwargs):
            """Override fill so that line is closed by default"""
            closed = kwargs.pop('closed', True)
            return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)
        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super(RadarAxes, self).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.concatenate((x, [x[0]]))
                y = np.concatenate((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):
            return self.draw_patch()
        def _gen_axes_spines(self):
            if frame == 'circle':
                return PolarAxes._gen_axes_spines(self)
            # The following is a hack to get the spines (i.e. the axes frame)
            # to draw correctly for a polygon frame.
            # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.
            spine_type = 'circle'
            verts = unit_poly_verts(theta + np.pi / 2)
            # close off polygon by repeating first vertex
            verts.append(verts[0])
            path = Path(verts)
            spine = Spine(self, spine_type, path)
            spine.set_transform(self.transAxes)
            return {'polar': spine}
    register_projection(RadarAxes)
    return theta

def unit_poly_verts(theta):
    """Return vertices of polygon for subplot axes.
    This polygon is circumscribed by a unit circle centered at (0.5, 0.5)
    """
    x0, y0, r = [0.5] * 3
    verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
    return verts

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)
    #     Pyrolized 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, axes = 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(axes.flatten(), 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)##填充
        ax.set_varlabels(spoke_labels)
    # add legend relative to top-left plot
    ax = axes[0, 0]
    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
    legend = ax.legend(labels, loc=(0.9, .95),
                       labelspacing=0.1, fontsize='small')
    fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
             horizontalalignment='center', color='black', weight='bold',
             size='large')
    plt.show()
    

第二个例子来自罗兵の水库的博客。因原代码在我电脑上有bug,不能完整显示图形,已更正,还略做了简化。

代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
'''
matplotlib雷达图
'''
import numpy as np
import matplotlib.pyplot as plt

# 雷达图
def plot_radar(labels, data, score):
    n = len(labels)
    # 转化为十分制!!!
    if score in [5, 10, 100]:
        data = data * 10/score
    elif score == 1:
        data = data * 10  
    angles = np.linspace(0, 2*np.pi, n, endpoint=False) 
    data = np.concatenate((data, [data[0]])) # 闭合
    angles = np.concatenate((angles, [angles[0]])) # 闭合
    
    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True)# 参数polar,表示极坐标!!
    # 画grid线(5条环形线)
    for i in [2,4,6,8,10]:
        ax.plot(angles, [i]*(n+1), 'k-',lw=0.5,) # 之所以 n +1,是因为要闭合!
    
     # 填充底色
    ax.fill(angles, [10]*(n+1), facecolor='lightgreen', alpha=0.2)
    # 自己画grid线(n条半径线)
    for i in range(n):
        ax.plot([angles[i], angles[i]], [0, 10], 'b-',lw=0.5)
        
    # 画线(数据)!
    ax.set_theta_zero_location( "N")#从正上方开始(对称比较美@_@)
    #ax.set_theta_zero_location(self, loc, offset=0.0), loc May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE".
    ax.plot(angles, data, 'b-', linewidth=2,marker = "o", markersize =5)
    # 填充
    ax.fill(angles, data, facecolor='r', alpha=1.0)

    grid_angles = [ i* 360.0/n for i in range(n)]
    ax.set_thetagrids(grid_angles, labels, fontproperties="SimHei") #grid_angles是角度制!!
    ax.set_title("matplotlib雷达图", va='bottom', fontproperties="SimHei", fontsize =14,color="g")
    
    ax.set_rlim(0,10)
    # 下两行去掉所有默认的grid线
    ax.spines['polar'].set_visible(False) # 去掉最外围的黑圈
    ax.grid(False)                        # 去掉中间的黑圈

    ax.set_yticks([])# 关闭径向数值刻度
    plt.show()
    
if __name__ == '__main__':
    labels = np.array(['水','火','风','云','雷','电']) #标签
    data = np.array([95,60,80,60,70,88]) # 数据
    score = 100 # 其可选的选项有1分制、5分制、10分制、100分制
    # 画雷达图
    plot_radar(labels, data, score)
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-05-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
重学springboot系列番外篇之RestTemplate
RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层的实现还是java应用开发中常用的一些HTTP客户端。但是相对于直接使用底层的HTTP客户端库,它的操作更加方便、快捷,能很大程度上提升我们的开发效率。
大忽悠爱学习
2021/12/15
4.9K0
重学springboot系列番外篇之RestTemplate
精讲RestTemplate第4篇-POST请求方法使用详解
在上一节为大家介绍了RestTemplate的GET请求的两个方法:getForObject()和getForEntity()。其实POST请求方法和GET请求方法上大同小异,RestTemplate的POST请求也包含两个主要方法:
字母哥博客
2020/09/23
13K0
精讲RestTemplate第4篇-POST请求方法使用详解
精讲RestTemplate第3篇-GET请求使用方法详解
二者的主要区别在于,getForObject()返回值是HTTP协议的响应体。getForEntity()返回的是ResponseEntity,ResponseEntity是对HTTP响应的封装,除了包含响应体,还包含HTTP状态码、contentType、contentLength、Header等信息。
字母哥博客
2020/09/23
6K0
精讲RestTemplate第3篇-GET请求使用方法详解
精讲RestTemplate第5篇-DELETE、PUT等请求方法使用详解
熟悉RESTful风格的朋友,应该了解RESTful风格API使用HTTP method表达对资源的操作。
字母哥博客
2020/09/23
1.9K0
精讲RestTemplate第5篇-DELETE、PUT等请求方法使用详解
精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用
RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层的实现还是java应用开发中常用的一些HTTP客户端。但是相对于直接使用底层的HTTP客户端库,它的操作更加方便、快捷,能很大程度上提升我们的开发效率。
字母哥博客
2020/09/23
1.4K0
精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用
Spring Data REST 与 Spring RestTemplate 实战详解
这篇分为两部分内容进行介绍(Spring Data REST 和 Spring RestTemplate)。我之前有一篇文章完整的介绍了 HTTP 协议的内容,而这两个工具中一个帮我们完成 Client 的实现,另一个帮我们完成 Server端的实现。 希望大家对 Spring 和 HTTP 之间有个完整的认识,并能够优雅地使用。 RestTemplate 认识 RestTemplate org.springframework.web.client.RestTemplate 位于 spring-web 的核
CSDN技术头条
2018/03/26
5.8K0
Spring Data REST 与 Spring RestTemplate 实战详解
使用Spring RestTemplate访问Rest服务
  上面这段是RestTemplate类中的简单介绍,RestTemplate是Spring3.0后开始提供的用于访问 Rest 服务的轻量级客户端,相较于传统的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大简化了发起HTTP请求以及处理响应的过程。本文关注RestTemplate是如何使用的,暂不涉及内部的实现原理。
happyJared
2018/09/20
1.7K0
使用Spring RestTemplate访问Rest服务
使用 RestTemplate 进行第三方Rest服务调用
RestTemplate 是 Spring 提供的一个调用 Restful 服务的抽象层,它简化的同 Restful 服务的通信方式,隐藏了不必要的一些细节,让我们更加优雅地在应用中调用 Restful 服务 。但是在 Spring 5.0 以后RestTemplate处于维护模式,不再进行新特性的开发,仅仅进行一些日常维护。Spring 建议我们使用同时支持同步、异步和 Stream 的另一个 API —— WebClient 。但是在 Spring MVC 下目前我们还没有更好的选择。
码农小胖哥
2020/04/17
1.5K0
使用 RestTemplate 进行第三方Rest服务调用
玩转Spring Boot之RestTemplate的使用
在java代码里想要进行restful web client服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。Spring Boot提供了一种简单便捷的内置模板类来进行操作,这就是RestTemplate。
闫同学
2022/10/31
7040
真不是我吹,Spring里这款牛逼的网络工具库我估计你都没用过!
传统情况下,在服务端代码里访问 http 服务时,我们一般会使用 JDK 的 HttpURLConnection 或者 Apache 的 HttpClient,不过这种方法使用起来太过繁琐,而且 api 使用起来非常的复杂,还得操心资源回收。
Java极客技术
2022/12/04
1.5K0
真不是我吹,Spring里这款牛逼的网络工具库我估计你都没用过!
SpringBoot图文教程17—上手就会 RestTemplate 使用指南「Get Post」「设置请求头」
问个问题:通过Java代码怎么发送Http请求,请求另一个Java程序的Controller方法呢?
鹿老师的Java笔记
2020/03/30
4K0
SpringBoot图文教程17—上手就会 RestTemplate 使用指南「Get Post」「设置请求头」
问个问题:通过Java代码怎么发送Http请求,请求另一个Java程序的Controller方法呢?
鹿老师的Java笔记
2020/03/20
2.2K0
重学SpringBoot3-RestTemplate配置与使用详解
RestTemplate 是 Spring 框架提供的一个用于发送 HTTP 请求的同步客户端工具类。在 SpringBoot 3.x 版本中,我们依然可以使用 RestTemplate 来进行 REST API 的调用。本文将详细介绍如何在 SpringBoot 3 项目中配置和使用 RestTemplate。
CoderJia
2024/12/02
1.5K0
重学SpringBoot3-RestTemplate配置与使用详解
SpringBoot系列之RestTemplate使用示例
博主之前经常对接一些接口,所以发现写一些http请求比较麻烦,学习springboot的过程知道可以用RestTemplate来做http请求,RestTemplate是Spring Framework框架封装的基于模板方法设计模式的一个工具类,带有同步模板方法 API 的原始 Spring REST 客户端类,下面博主分析一些对接过程的一些经验,RestTemplate基本使用可以参考官网文档:https://docs.spring.io/spring-framework/docs/5.1.6.RELEASE/spring-framework-reference/integration.html#rest-client-access
SmileNicky
2022/05/07
1.6K0
SpringBoot系列之RestTemplate使用示例
一文吃透接口调用神器RestTemplate
发送 http 请求,估计很多人用过 httpclient 和 okhttp,确实挺好用的,而 Spring web 中的 RestTemplate 和这俩的功能类似,也是用来发送 http 请求的,不过用法上面比前面的 2 位要容易很多。
路人甲Java
2021/11/08
12K0
一文吃透接口调用神器RestTemplate
Springboot — 用更优雅的方式发HTTP请求(RestTemplate详解)
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
Java_老男孩
2019/12/02
11.6K1
RestTemplate用法
RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都
鱼找水需要时间
2023/02/16
4520
Spring之RestTemplate使用小结一
作为一个Java后端,需要通过HTTP请求其他的网络资源可以说是一个比较常见的case了;一般怎么做呢?
一灰灰blog
2018/08/13
6.5K0
Spring之RestTemplate使用小结一
springboot-1-restTemplate的使用
原博客: http://blog.csdn.net/u013895412/article/details/53096855
用户5640963
2019/07/26
1.1K0
一起学 Spring 之 RestTemplate
在 Java 服务端开发领域里,Spring 是绕不开的话题,尤其是现在微服务概念盛行,Spring Boot 的出现更是给 Spring 注入了新的活力,除此之外还有 Spring Cloud,这些框架让 Spring 技术体系更加丰富。Spring 从 2014 年的 1.0.0 版本迭代到 现在的 5.2.0 M1 版本,紧随着 Java 语言发展,不断引入新的特性和功能。
闻人的技术博客
2019/09/19
1.5K0
一起学 Spring 之 RestTemplate
推荐阅读
相关推荐
重学springboot系列番外篇之RestTemplate
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档