Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >matplotlib 雷达图/蛛网图

matplotlib 雷达图/蛛网图

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

本篇讲解如何用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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
深度学习基础之matplotlib,一文搞定各个示例
Matplotlib 是 Python 的绘图库。它可与 NumPy 一起使用 ,Matplotlib也是深度学习的常用绘图库,主要是将训练的成果进行图形化,因为这样更直观,更方便发现训练中的问题,今天来学习下,走起!!
香菜聊游戏
2021/10/19
1.5K0
深度学习基础之matplotlib,一文搞定各个示例
Python数据分析之matplotlib(应用篇)
matplotlib核心剖析(http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html#commentform)
AI异构
2020/07/29
3420
Python数据分析之matplotlib(应用篇)
25 个常用 Matplotlib 图的 Python 代码,收藏收藏!
大家好,今天要分享给大家25个Matplotlib图的汇总,在数据分析和可视化中非常有用,文章较长,可以马起来慢慢练手。
Python数据科学
2020/05/26
8430
绘图技巧 | 我总结了雷达图的绘制方法(R+Python)
今天给大家介绍的的图表为雷达图(Radar/Spider chart),这种类型图表在生活中较常使用,是一种以从同一点开始的轴上表示的三个或更多个定量变量的二维图表的形式显示多变量数据的图形方法。较常用的场景多为分析企业经营状况(收益性、生产性、流动性、安全性和成长性)。本期推文带你使R-Python绘制雷达图,主要内容如下:
DataCharm
2021/04/16
5.6K0
绘图技巧 | 我总结了雷达图的绘制方法(R+Python)
又再肝3天,整理了65个Matplotlib案例,这能不收藏?
Matplotlib 作为 Python 家族当中最为著名的画图工具,基本的操作还是要掌握的,今天就来分享一波
周萝卜
2021/11/08
2.5K0
深度好文 | Matplotlib 可视化最有价值的 50 个图表(附完整 Python 源代码)
在数据分析和可视化中最有用的 50 个 Matplotlib 图表。 这些图表列表允许您使用 python 的 matplotlib 和 seaborn 库选择要显示的可视化对象。
数据派THU
2019/05/09
1.7K0
深度好文 | Matplotlib 可视化最有价值的 50 个图表(附完整 Python 源代码)
利用Python绘制全国各省新型冠状病毒疫情变化动态图
题图:Image by enriquelopezgarre from Pixabay
猴哥yuri
2020/02/25
2.6K0
Python数据可视化-第6章-坐标轴的定制
matplotlib支持向画布的任意位置添加自定义大小的绘图区域,同时显示坐标轴。通过pyplot模块的axes()函数创建一个Axes类的对象,并将Axes类的对象添加到当前画布中。
用户2225445
2025/04/04
1770
Python数据可视化-第6章-坐标轴的定制
使用Matplotlib对数据进行高级可视化(基本图,3D图和小部件)
可视化在当今世界许多领域的结果传播中发挥着重要作用。如果没有适当的可视化,很难揭示结果,理解变量之间的复杂关系并描述数据的趋势。
代码医生工作室
2019/06/21
3.9K0
使用Matplotlib对数据进行高级可视化(基本图,3D图和小部件)
python matplotlib各种绘图类型完整总结
plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)
Twcat_tree
2022/12/05
6K0
python matplotlib各种绘图类型完整总结
Matplotlib 1.4W+字基础教程来了(收藏吃灰去吧~~)
参考:Rougier N P, Droettboom M, Bourne P E, et al. Ten Simple Rules for Better Figures[J]. PLOS Computational Biology【IF 4.7】, 2014, 10(9).感兴趣戳:https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4161295/pdf/pcbi.1003833.pdf
DataCharm
2021/02/22
1.5K0
Matplotlib 1.4W+字基础教程来了(收藏吃灰去吧~~)
Python matplotlib绘制雷达图
雷达图也被称为网络图,蜘蛛图,星图,蜘蛛网图,是一个不规则的多边形。雷达图可以形象地展示相同事物的多维指标,应用场景非常多。
Python碎片公众号
2021/02/26
3K0
Python matplotlib绘制雷达图
matplotlib进阶:Artist
FigureCanvas 和 Renderer 解决和用户界面(如 wxPython)或绘图语言(如 PostScript)间通信的所有细节。而Artists 解决figure,text,lines这些元素的呈现和布局相关的所有细节。通常95%的时间都会花在 Artists 上。
bugsuse
2020/04/21
1.5K0
matplotlib进阶:Artist
matplotlib 3D 绘图(二)
四. 3D 散点图 from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np
用户6021899
2019/08/14
8030
数据分析最有用的Top 50 Matplotlib图(带有完整的Python代码)(上)
50个Matplotlib图的汇编,在数据分析和可视化中最有用。此列表允许您使用Python的Matplotlib和Seaborn库选择要显示的可视化对象。
Datawhale
2019/10/18
2.1K0
数据分析最有用的Top 50 Matplotlib图(带有完整的Python代码)(上)
matplotlib安装及使用
matplotlib是基于python语言的开源项目,旨在为python提供一个数据绘图包。我将在这篇文章中介绍matplotlib API的核心对象,并介绍如何使用这些对象来实现绘图。实际上,matplotlib的对象体系严谨而有趣,为使用者提供了巨大的发挥空间。用户在熟悉了核心对象之后,可以轻易的定制图像。matplotlib的对象体系也是计算机图形学的一个优秀范例。即使你不是python程序员,你也可以从文中了解一些通用的图形绘制原则。matplotlib使用numpy进行数组运算,并调用一系列其他的python库来实现硬件交互。matplotlib的核心是一套由对象构成的绘图API。
狼啸风云
2023/10/07
5120
matplotlib安装及使用
Matplotlib从入门到精通02-层次元素和容器
参考: https://datawhalechina.github.io/fantastic-matplotlib/%E7%AC%AC%E4%B8%80%E5%9B%9E%EF%BC%9AMatplotlib%E5%88%9D%E7%9B%B8%E8%AF%86/index.html
用户2225445
2023/10/16
5170
Matplotlib从入门到精通02-层次元素和容器
数据可视化基础与应用-03-matplotlib库从入门到精通01-05
本系列是数据可视化基础与应用的第03篇,主要介绍基于matplotlib实现数据可视化。
用户2225445
2024/03/21
8870
数据可视化基础与应用-03-matplotlib库从入门到精通01-05
Matplotlib 可视化最有价值的 14 个图表(附完整 Python 源代码)
这些图表根据可视化目标的7个不同情景进行分组。 例如,如果要想象两个变量之间的关系,请查看“关联”部分下的图表。 或者,如果您想要显示值如何随时间变化,请查看“变化”部分,依此类推。
CSDN技术头条
2019/11/19
1.1K0
Matplotlib 可视化最有价值的 14 个图表(附完整 Python 源代码)
python下Matplotlib绘图案例与常见设置简介
首先一幅Matplotlib的图像组成部分介绍。 基本构成 在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个或者多个Axes对象。每个Axes(ax)对象都是
学到老
2018/04/17
1.5K0
python下Matplotlib绘图案例与常见设置简介
推荐阅读
相关推荐
深度学习基础之matplotlib,一文搞定各个示例
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验