当前位置: 首页 > news >正文

泰勒雷达图2

matplotlib绘制泰勒雷达图

import matplotlib.pyplot as plt
import numpy as np
from numpy.core.fromnumeric import shape
import pandas as pd
import dask.dataframe as dd
from matplotlib.projections import PolarAxes
import mpl_toolkits.axisartist.floating_axes as FA
import mpl_toolkits.axisartist.grid_finder as GF
from matplotlib.transforms import Affine2Dclass TaylorDiagram:"""ref: pandas.DataFrame one columnsamples: pandas.DataFrame multiple columns"""def __init__(self, ax, ref, samples, Normalize=False, markers=[], colors=[], scale=1.2, ms=10, pkwargs={}):self.points = []self.Normalize = Normalizeself.pkwargs = pkwargsself.markers = markers if len(markers) else ['o', 'o', 's', 'v', 'o', 's', 'v'] * 100self.colors = colors if len(colors) else ['tab:blue', 'tab:red', 'tab:red', 'tab:red', 'tab:green', 'tab:green', 'tab:green', '#1abc9c', '#2ecc71', '#3498db', '#9b59b6', '#34495e']self.ms = msself.ref = refself.scale = scaleself.samples = samplesself.fig = plt.gcf()  # get current figureself.step_up(ax)  # set up a diagram axesself.plot_sample()  # draw sample points# self.add_legend()  # add legenddef calc_loc(self, x, y):# x为参考数据,y为评估数据# theta为弧度;r为半径R = x.corr(other=y, method='pearson')theta = np.arccos(R)r = y.std()return theta, r / self._refstd if self.Normalize else rdef step_up(self, ax):# close the original axisax.axis('off')ll, bb, ww, hh = ax.get_position().bounds# polar transformtr = PolarAxes.PolarTransform()# theta rangeRlocs = np.array([0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1])Tlocs = np.arccos(Rlocs)  # convrt to theta locations# grid findergl1 = GF.FixedLocator(Tlocs)  # theta locatortf1 = GF.DictFormatter(dict(zip(Tlocs, map(str, Rlocs))))  # theta formatter# std rangeself._refstd = self.ref.std()self.stdmax = max([self.samples[col].std() for col in self.samples.columns] + [self._refstd])self.Smax = (1 if self.Normalize else self.stdmax)* self.scaleself.refstd = 1 if self.Normalize else self._refstdSlocs = np.linspace(0, self.Smax, 4)gl2 = GF.FixedLocator(Slocs)  # theta locatortf2 = GF.DictFormatter(dict(zip(Slocs, map(lambda i: '%.1f' % i, Slocs))))  # theta formatter# construct grid helpergrid_helper = FA.GridHelperCurveLinear(tr, extremes=(0, np.pi / 2, 0, self.Smax),grid_locator1=gl1, tick_formatter1=tf1,grid_locator2=gl2, tick_formatter2=tf2,)ax = self.fig.add_axes([ll, bb, ww, hh], facecolor='none', axes_class=FA.FloatingAxes, grid_helper=grid_helper)# thetaax.axis["top"].set_axis_direction("bottom")ax.axis["top"].toggle(ticklabels=True, label=True)ax.axis["top"].major_ticklabels.set_axis_direction("top")ax.axis["top"].label.set_axis_direction("top")ax.axis["top"].label.set_text("Correlation")ax.axis["top"].major_ticklabels.set_pad(8)# std leftax.axis["left"].set_axis_direction("bottom")ax.axis["left"].toggle(ticklabels=True)# std bottomax.axis["right"].set_axis_direction("top")ax.axis["right"].toggle(ticklabels=True, label=True)ax.axis["right"].label.set_text("Standard deviation")ax.axis["right"].major_ticklabels.set_axis_direction("left")ax.axis["right"].major_ticklabels.set_pad(8)# hideax.axis['bottom'].set_visible(False)# draw gridax.grid(linestyle='--', color='gray')self._ax = axself.ax = ax.get_aux_axes(tr)# STD线t = np.linspace(0, np.pi/2)r = np.zeros_like(t) + self.refstdself.ax.plot(t, r, 'k--')# RMS格网rs, ts = np.meshgrid(np.linspace(0, self.Smax, 100), np.linspace(0, np.pi/2, 100))rms = (self.refstd**2 + rs**2 - 2*self.refstd*rs*np.cos(ts))**0.5contours = self.ax.contour(ts, rs, rms, levels=np.linspace(0, self.scale, 4) if self.Normalize else 4,colors='gray', linestyles='--', alpha=.5)self.ax.clabel(contours, contours.levels, inline=True, fmt='%.1f', fontsize=10)# 绘制参考点p, = self.ax.plot(0, self.refstd, linestyle='', marker=self.markers[0], color=self.colors[0],markersize=self.ms, alpha=0.5, **self.pkwargs)p.set_label(self.ref.name)p.set_clip_on(True)  # reference点不被裁剪self.points.append(p)def plot_sample(self):stds = []for col, marker, color in zip(self.samples.columns, self.markers[1:], self.colors[1:]):t, s = self.calc_loc(self.ref, self.samples[col])p, = self.ax.plot(t, s, linestyle='', marker=marker, color=color, markersize=self.ms, alpha=.5, **self.pkwargs)p.set_label(col)self.points.append(p)stds.append(s)self.ax.set_xlim(xmax=max(stds))def add_legend(self):ll, bb, ww, hh = self.ax.get_position().boundsself.ax.legend(ncol=len(self.samples) + 1, loc='lower center', frameon=False, bbox_to_anchor=(ll, bb - hh*0.3, ww, hh*0.1))
if __name__ == "__main__":print('read data')df =pd.read_csv(r'C:\Users\Administrator\Desktop\123.csv')
#     df=pd.DataFrame(df)
#     print(df)fig, axes = plt.subplots(1, 1, figsize=(5, 5))td = TaylorDiagram(axes,df.iloc[:, 0], df.iloc[:,1:], ms=20, Normalize=True, scale=1.5)plt.show()

在这里插入图片描述

http://www.lryc.cn/news/395359.html

相关文章:

  • 数据库容灾 | MySQL MGR与阿里云PolarDB-X Paxos的深度对比
  • react根据后端返回数据动态添加路由
  • 机器学习中的可解释性
  • 上海慕尼黑电子展开展,启明智显携物联网前沿方案亮相
  • Centos7离线安装ElasticSearch7.4.2
  • 深入理解sklearn中的模型参数优化技术
  • 【Elasticsearch】开源搜索技术的演进与选择:Elasticsearch 与 OpenSearch
  • 欧拉openEuler 22.03 LTS-部署k8sv1.03.1
  • 老年生活照护实训室:为养老服务业输送专业人才
  • go语言中使用WaitGroup和channel实现处理多线程问题
  • Open3D 计算点云的平均密度
  • C语言之数据在内存中的存储(1),整形与大小端字节序
  • B端全局导航:左侧还是顶部?不是随随便便,有依据在。
  • 什么是海外仓管理自动化?策略及落地实施步骤指南
  • 自定义控件三部曲之绘图篇(六)Paint之函数大汇总、ColorMatrix与滤镜效果、setColorFilter
  • 请写sql满足业务:找到连续登录3天以上的用户
  • fatal error: apriltag/apriltag.h: No such file or directory 的 参考解决方法
  • C++继承(一文说懂)
  • 卷积神经网络可视化的探索
  • RxJava学习记录
  • Spring Boot Vue 毕设系统讲解 3
  • Spring Boot对接大模型:实战价值与技巧
  • 完美解决NameError: name ‘file‘ is not defined的正确解决方法,亲测有效!!!
  • Witness Table 的由来
  • Python 3 AI 编程助手
  • 【nginx】nginx的配置文件到底是什么结构,到底怎么写?
  • 基于React 实现井字棋
  • 文件的换行符,Windows 的 CRLF 和 Linux 的 LF
  • 怎样优化 PostgreSQL 中对日期时间范围的模糊查询?
  • B端设计:任何不顾及用户体验的设计,都是在装样子,花架子