我有一个简单的问题 我想创建一个雷达图,如示例 here 中所示。因为我只需要一个雷达并且我想要默认颜色,所以我选择修改示例。
第一步效果很好。但是在更改雷达上的标签时,我遇到了一个问题。我使用的名字是长和穿越那个情节本身。
another question 有类似的问题,但当时的解决方案已贬值。
在其中一条评论中说当前方法是 set_pad()
。
直到没有我至少锻炼了很多不起作用的解决方案......我遇到的两个错误是
AttributeError: type object '...' has no attribute 'set_pad'
和
AttributeError: 'RadarAxesSubplot' object has no attribute '...'
我目前拥有的代码是这样的:
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():
# The following data is from the Denver Aerosol Sources and Health study.
# See doi:10.1016/j.atmosenv.2008.12.017
#
# ...
data = [
['Sulfate', 'Nitrate', 'a long string', 'Abbr.', 'a string', 'b string', 'another longs string', 's str', 'sh str'],
('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]])
]
return data
if __name__ == '__main__':
N = 9
theta = radar_factory(N) # , frame='polygon')
data = example_data()
title = data[1][0]
spoke_labels = data.pop(0)
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111, projection='radar')
# ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.5), horizontalalignment='center', verticalalignment='center')
case_data = data[0][1]
caseiter = [0, 1, 2]
for d in zip(case_data):
print(d)
ax.plot(theta, d[0])
ax.fill(theta, d[0], alpha=0.25)
ax.set_varlabels(spoke_labels) # , frac=1.5)
# ax.axis.ThetaTick.set_pad(20) # in pixels
# ax.axis.XTick.set_pad(20) # in pixels
ax.set_theta_direction(-1)
ax.set_yticklabels([])
# add legend relative to top-left plot
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, 1, 'Experiences',
horizontalalignment='center', color='black', weight='bold',
size='large')
plt.show()
这是当前的结果。
对我来说,是否所有标签都有一个偏移量或文本的对齐从圆圈开始都没有关系。
答案 0 :(得分:1)
一些想法(可以根据您的数据组合这些想法):
plt.tight_layout()
,这样图例和刻度标签将很好地融入图中在给定的代码中,我将函数 set_varlabels()
更改如下:
def set_varlabels(self, labels):
labels_with_newlines = [l.replace(' ', '\n') for l in labels]
_lines, texts = self.set_thetagrids(np.degrees(theta), labels_with_newlines)
half = (len(texts) - 1) // 2
for t in texts[1:half]:
t.set_horizontalalignment('left')
for t in texts[-half + 1:]:
t.set_horizontalalignment('right')
我还使用了 loc=(1.2, 0.95)
作为图例,并在最后调用了 plt.tight_layout()
。
它看起来像: