Python 雷达图中的置信区间(区域未关闭)
我试图在雷达图中绘制包含置信区间的数据 我遵循matplotlib文档并进行了更改以添加错误区域,但它显示了Cat.1和Cat.9之间的空白区域,如图所示。 当我在θ计算中将端点设置为true时,我丢失了一个数据点 如何在不丢失数据点的情况下修复它 以下是修改后的代码:Python 雷达图中的置信区间(区域未关闭),python,matplotlib,visualization,Python,Matplotlib,Visualization,我试图在雷达图中绘制包含置信区间的数据 我遵循matplotlib文档并进行了更改以添加错误区域,但它显示了Cat.1和Cat.9之间的空白区域,如图所示。 当我在θ计算中将端点设置为true时,我丢失了一个数据点 如何在不丢失数据点的情况下修复它 以下是修改后的代码: import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, RegularPolygon from ma
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 RadarAxes(PolarAxes):
name = 'radar'
# use 1 line segment to connect specified points
RESOLUTION = 1
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():
data = [
['Cat. 1', 'Cat. 2', 'Cat. 3', 'Cat. 4', 'Cat. 5', 'Cat. 6', 'Cat. 7', 'Cat. 8', 'Cat. 9'],
('mean1', [
[5, 5, 5, 5, 5, 5, 5, 5, 5]]),
('upper1', [
[6, 6, 6, 6, 6, 6, 6, 6, 6]]),
('lower1', [
[4, 4, 4, 4, 4, 4, 4, 4, 4]]),
('mean2', [
[2, 2, 2, 2, 2, 2, 2, 2, 2]]),
('upper2', [
[3, 3, 3, 3, 3, 3, 3, 3, 3]]),
('lower2', [
[1, 1, 1, 1, 1, 1, 1, 1, 1]])
]
return data
if __name__ == '__main__':
N = 9
theta = radar_factory(N, frame='circle')
data = example_data()
labels = data.pop(0)
mean_data=[data[0][1], data[3][1]]
upper_data=[data[1][1], data[4][1]]
lower_data=[data[2][1], data[5][1]]
fig, axs = plt.subplots(figsize=(9, 9), nrows=1, ncols=1,
subplot_kw=dict(projection='radar'))
fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)
colors = ['b', 'r']
# Plot the two cases from the example data on separate axes
for d, u, l, color in zip(mean_data, upper_data, lower_data, colors):
axs.plot(theta, d[0], color=color)
axs.fill_between(theta, u[0], l[0], facecolor=color, alpha=0.2)
axs.set_varlabels(labels)
# add legend relative to top-left plot
labels = ('Factor 1', 'Factor 2')
legend = axs.legend(labels, loc=(0.9, .95),
labelspacing=0.1, fontsize='small')
plt.show()
我修改了前面提到的代码,添加了置信区间,它可以正常工作,请参见
categories =['Cat. 1', 'Cat. 2', 'Cat. 3', 'Cat. 4', 'Cat. 5', 'Cat. 6', 'Cat. 7', 'Cat. 8', 'Cat. 9']
categories = [*categories, categories[0]]
mean = [5, 5, 5, 5, 5, 5, 5, 5, 5]
upper = [6, 6, 6, 6, 6, 6, 6, 6, 6]
lower = [4, 4, 4, 4, 4, 4, 4, 4, 4]
mean = [*mean, mean[0]]
upper = [*upper, upper[0]]
lower = [*lower, lower[0]]
mean1= [2, 2, 2, 2, 2, 2, 2, 2, 2]
upper1=[3, 3, 3, 3, 3, 3, 3, 3, 3]
lower1=[1, 1, 1, 1, 1, 1, 1, 1, 1]
mean1 = [*mean1, mean1[0]]
upper1 = [*upper1, upper1[0]]
lower1 = [*lower1, lower1[0]]
label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(mean))
plt.figure(figsize=(8, 8))
plt.subplot(polar=True)
plt.plot(label_loc, mean, label='Factor 1',color='b')
plt.fill_between(label_loc, upper, lower, facecolor='b', alpha=0.2)
plt.subplot(polar=True)
plt.plot(label_loc, mean1, label='Factor 2',color='r')
plt.fill_between(label_loc, upper1, lower1, facecolor='r', alpha=0.2)
lines, labels = plt.thetagrids(np.degrees(label_loc), labels=categories)
plt.legend()
plt.show()