polar.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. import math
  2. import types
  3. import numpy as np
  4. import matplotlib as mpl
  5. from matplotlib import _api, cbook
  6. from matplotlib.axes import Axes
  7. import matplotlib.axis as maxis
  8. import matplotlib.markers as mmarkers
  9. import matplotlib.patches as mpatches
  10. from matplotlib.path import Path
  11. import matplotlib.ticker as mticker
  12. import matplotlib.transforms as mtransforms
  13. from matplotlib.spines import Spine
  14. class PolarTransform(mtransforms.Transform):
  15. r"""
  16. The base polar transform.
  17. This transform maps polar coordinates :math:`\theta, r` into Cartesian
  18. coordinates :math:`x, y = r \cos(\theta), r \sin(\theta)`
  19. (but does not fully transform into Axes coordinates or
  20. handle positioning in screen space).
  21. This transformation is designed to be applied to data after any scaling
  22. along the radial axis (e.g. log-scaling) has been applied to the input
  23. data.
  24. Path segments at a fixed radius are automatically transformed to circular
  25. arcs as long as ``path._interpolation_steps > 1``.
  26. """
  27. input_dims = output_dims = 2
  28. def __init__(self, axis=None, use_rmin=True,
  29. _apply_theta_transforms=True, *, scale_transform=None):
  30. """
  31. Parameters
  32. ----------
  33. axis : `~matplotlib.axis.Axis`, optional
  34. Axis associated with this transform. This is used to get the
  35. minimum radial limit.
  36. use_rmin : `bool`, optional
  37. If ``True``, subtract the minimum radial axis limit before
  38. transforming to Cartesian coordinates. *axis* must also be
  39. specified for this to take effect.
  40. """
  41. super().__init__()
  42. self._axis = axis
  43. self._use_rmin = use_rmin
  44. self._apply_theta_transforms = _apply_theta_transforms
  45. self._scale_transform = scale_transform
  46. __str__ = mtransforms._make_str_method(
  47. "_axis",
  48. use_rmin="_use_rmin",
  49. _apply_theta_transforms="_apply_theta_transforms")
  50. def _get_rorigin(self):
  51. # Get lower r limit after being scaled by the radial scale transform
  52. return self._scale_transform.transform(
  53. (0, self._axis.get_rorigin()))[1]
  54. @_api.rename_parameter("3.8", "tr", "values")
  55. def transform_non_affine(self, values):
  56. # docstring inherited
  57. theta, r = np.transpose(values)
  58. # PolarAxes does not use the theta transforms here, but apply them for
  59. # backwards-compatibility if not being used by it.
  60. if self._apply_theta_transforms and self._axis is not None:
  61. theta *= self._axis.get_theta_direction()
  62. theta += self._axis.get_theta_offset()
  63. if self._use_rmin and self._axis is not None:
  64. r = (r - self._get_rorigin()) * self._axis.get_rsign()
  65. r = np.where(r >= 0, r, np.nan)
  66. return np.column_stack([r * np.cos(theta), r * np.sin(theta)])
  67. def transform_path_non_affine(self, path):
  68. # docstring inherited
  69. if not len(path) or path._interpolation_steps == 1:
  70. return Path(self.transform_non_affine(path.vertices), path.codes)
  71. xys = []
  72. codes = []
  73. last_t = last_r = None
  74. for trs, c in path.iter_segments():
  75. trs = trs.reshape((-1, 2))
  76. if c == Path.LINETO:
  77. (t, r), = trs
  78. if t == last_t: # Same angle: draw a straight line.
  79. xys.extend(self.transform_non_affine(trs))
  80. codes.append(Path.LINETO)
  81. elif r == last_r: # Same radius: draw an arc.
  82. # The following is complicated by Path.arc() being
  83. # "helpful" and unwrapping the angles, but we don't want
  84. # that behavior here.
  85. last_td, td = np.rad2deg([last_t, t])
  86. if self._use_rmin and self._axis is not None:
  87. r = ((r - self._get_rorigin())
  88. * self._axis.get_rsign())
  89. if last_td <= td:
  90. while td - last_td > 360:
  91. arc = Path.arc(last_td, last_td + 360)
  92. xys.extend(arc.vertices[1:] * r)
  93. codes.extend(arc.codes[1:])
  94. last_td += 360
  95. arc = Path.arc(last_td, td)
  96. xys.extend(arc.vertices[1:] * r)
  97. codes.extend(arc.codes[1:])
  98. else:
  99. # The reverse version also relies on the fact that all
  100. # codes but the first one are the same.
  101. while last_td - td > 360:
  102. arc = Path.arc(last_td - 360, last_td)
  103. xys.extend(arc.vertices[::-1][1:] * r)
  104. codes.extend(arc.codes[1:])
  105. last_td -= 360
  106. arc = Path.arc(td, last_td)
  107. xys.extend(arc.vertices[::-1][1:] * r)
  108. codes.extend(arc.codes[1:])
  109. else: # Interpolate.
  110. trs = cbook.simple_linear_interpolation(
  111. np.vstack([(last_t, last_r), trs]),
  112. path._interpolation_steps)[1:]
  113. xys.extend(self.transform_non_affine(trs))
  114. codes.extend([Path.LINETO] * len(trs))
  115. else: # Not a straight line.
  116. xys.extend(self.transform_non_affine(trs))
  117. codes.extend([c] * len(trs))
  118. last_t, last_r = trs[-1]
  119. return Path(xys, codes)
  120. def inverted(self):
  121. # docstring inherited
  122. return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin,
  123. self._apply_theta_transforms)
  124. class PolarAffine(mtransforms.Affine2DBase):
  125. r"""
  126. The affine part of the polar projection.
  127. Scales the output so that maximum radius rests on the edge of the axes
  128. circle and the origin is mapped to (0.5, 0.5). The transform applied is
  129. the same to x and y components and given by:
  130. .. math::
  131. x_{1} = 0.5 \left [ \frac{x_{0}}{(r_{\max} - r_{\min})} + 1 \right ]
  132. :math:`r_{\min}, r_{\max}` are the minimum and maximum radial limits after
  133. any scaling (e.g. log scaling) has been removed.
  134. """
  135. def __init__(self, scale_transform, limits):
  136. """
  137. Parameters
  138. ----------
  139. scale_transform : `~matplotlib.transforms.Transform`
  140. Scaling transform for the data. This is used to remove any scaling
  141. from the radial view limits.
  142. limits : `~matplotlib.transforms.BboxBase`
  143. View limits of the data. The only part of its bounds that is used
  144. is the y limits (for the radius limits).
  145. """
  146. super().__init__()
  147. self._scale_transform = scale_transform
  148. self._limits = limits
  149. self.set_children(scale_transform, limits)
  150. self._mtx = None
  151. __str__ = mtransforms._make_str_method("_scale_transform", "_limits")
  152. def get_matrix(self):
  153. # docstring inherited
  154. if self._invalid:
  155. limits_scaled = self._limits.transformed(self._scale_transform)
  156. yscale = limits_scaled.ymax - limits_scaled.ymin
  157. affine = mtransforms.Affine2D() \
  158. .scale(0.5 / yscale) \
  159. .translate(0.5, 0.5)
  160. self._mtx = affine.get_matrix()
  161. self._inverted = None
  162. self._invalid = 0
  163. return self._mtx
  164. class InvertedPolarTransform(mtransforms.Transform):
  165. """
  166. The inverse of the polar transform, mapping Cartesian
  167. coordinate space *x* and *y* back to *theta* and *r*.
  168. """
  169. input_dims = output_dims = 2
  170. def __init__(self, axis=None, use_rmin=True,
  171. _apply_theta_transforms=True):
  172. """
  173. Parameters
  174. ----------
  175. axis : `~matplotlib.axis.Axis`, optional
  176. Axis associated with this transform. This is used to get the
  177. minimum radial limit.
  178. use_rmin : `bool`, optional
  179. If ``True`` add the minimum radial axis limit after
  180. transforming from Cartesian coordinates. *axis* must also be
  181. specified for this to take effect.
  182. """
  183. super().__init__()
  184. self._axis = axis
  185. self._use_rmin = use_rmin
  186. self._apply_theta_transforms = _apply_theta_transforms
  187. __str__ = mtransforms._make_str_method(
  188. "_axis",
  189. use_rmin="_use_rmin",
  190. _apply_theta_transforms="_apply_theta_transforms")
  191. @_api.rename_parameter("3.8", "xy", "values")
  192. def transform_non_affine(self, values):
  193. # docstring inherited
  194. x, y = values.T
  195. r = np.hypot(x, y)
  196. theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)
  197. # PolarAxes does not use the theta transforms here, but apply them for
  198. # backwards-compatibility if not being used by it.
  199. if self._apply_theta_transforms and self._axis is not None:
  200. theta -= self._axis.get_theta_offset()
  201. theta *= self._axis.get_theta_direction()
  202. theta %= 2 * np.pi
  203. if self._use_rmin and self._axis is not None:
  204. r += self._axis.get_rorigin()
  205. r *= self._axis.get_rsign()
  206. return np.column_stack([theta, r])
  207. def inverted(self):
  208. # docstring inherited
  209. return PolarAxes.PolarTransform(self._axis, self._use_rmin,
  210. self._apply_theta_transforms)
  211. class ThetaFormatter(mticker.Formatter):
  212. """
  213. Used to format the *theta* tick labels. Converts the native
  214. unit of radians into degrees and adds a degree symbol.
  215. """
  216. def __call__(self, x, pos=None):
  217. vmin, vmax = self.axis.get_view_interval()
  218. d = np.rad2deg(abs(vmax - vmin))
  219. digits = max(-int(np.log10(d) - 1.5), 0)
  220. # Use Unicode rather than mathtext with \circ, so that it will work
  221. # correctly with any arbitrary font (assuming it has a degree sign),
  222. # whereas $5\circ$ will only work correctly with one of the supported
  223. # math fonts (Computer Modern and STIX).
  224. return f"{np.rad2deg(x):0.{digits:d}f}\N{DEGREE SIGN}"
  225. class _AxisWrapper:
  226. def __init__(self, axis):
  227. self._axis = axis
  228. def get_view_interval(self):
  229. return np.rad2deg(self._axis.get_view_interval())
  230. def set_view_interval(self, vmin, vmax):
  231. self._axis.set_view_interval(*np.deg2rad((vmin, vmax)))
  232. def get_minpos(self):
  233. return np.rad2deg(self._axis.get_minpos())
  234. def get_data_interval(self):
  235. return np.rad2deg(self._axis.get_data_interval())
  236. def set_data_interval(self, vmin, vmax):
  237. self._axis.set_data_interval(*np.deg2rad((vmin, vmax)))
  238. def get_tick_space(self):
  239. return self._axis.get_tick_space()
  240. class ThetaLocator(mticker.Locator):
  241. """
  242. Used to locate theta ticks.
  243. This will work the same as the base locator except in the case that the
  244. view spans the entire circle. In such cases, the previously used default
  245. locations of every 45 degrees are returned.
  246. """
  247. def __init__(self, base):
  248. self.base = base
  249. self.axis = self.base.axis = _AxisWrapper(self.base.axis)
  250. def set_axis(self, axis):
  251. self.axis = _AxisWrapper(axis)
  252. self.base.set_axis(self.axis)
  253. def __call__(self):
  254. lim = self.axis.get_view_interval()
  255. if _is_full_circle_deg(lim[0], lim[1]):
  256. return np.arange(8) * 2 * np.pi / 8
  257. else:
  258. return np.deg2rad(self.base())
  259. def view_limits(self, vmin, vmax):
  260. vmin, vmax = np.rad2deg((vmin, vmax))
  261. return np.deg2rad(self.base.view_limits(vmin, vmax))
  262. class ThetaTick(maxis.XTick):
  263. """
  264. A theta-axis tick.
  265. This subclass of `.XTick` provides angular ticks with some small
  266. modification to their re-positioning such that ticks are rotated based on
  267. tick location. This results in ticks that are correctly perpendicular to
  268. the arc spine.
  269. When 'auto' rotation is enabled, labels are also rotated to be parallel to
  270. the spine. The label padding is also applied here since it's not possible
  271. to use a generic axes transform to produce tick-specific padding.
  272. """
  273. def __init__(self, axes, *args, **kwargs):
  274. self._text1_translate = mtransforms.ScaledTranslation(
  275. 0, 0, axes.figure.dpi_scale_trans)
  276. self._text2_translate = mtransforms.ScaledTranslation(
  277. 0, 0, axes.figure.dpi_scale_trans)
  278. super().__init__(axes, *args, **kwargs)
  279. self.label1.set(
  280. rotation_mode='anchor',
  281. transform=self.label1.get_transform() + self._text1_translate)
  282. self.label2.set(
  283. rotation_mode='anchor',
  284. transform=self.label2.get_transform() + self._text2_translate)
  285. def _apply_params(self, **kwargs):
  286. super()._apply_params(**kwargs)
  287. # Ensure transform is correct; sometimes this gets reset.
  288. trans = self.label1.get_transform()
  289. if not trans.contains_branch(self._text1_translate):
  290. self.label1.set_transform(trans + self._text1_translate)
  291. trans = self.label2.get_transform()
  292. if not trans.contains_branch(self._text2_translate):
  293. self.label2.set_transform(trans + self._text2_translate)
  294. def _update_padding(self, pad, angle):
  295. padx = pad * np.cos(angle) / 72
  296. pady = pad * np.sin(angle) / 72
  297. self._text1_translate._t = (padx, pady)
  298. self._text1_translate.invalidate()
  299. self._text2_translate._t = (-padx, -pady)
  300. self._text2_translate.invalidate()
  301. def update_position(self, loc):
  302. super().update_position(loc)
  303. axes = self.axes
  304. angle = loc * axes.get_theta_direction() + axes.get_theta_offset()
  305. text_angle = np.rad2deg(angle) % 360 - 90
  306. angle -= np.pi / 2
  307. marker = self.tick1line.get_marker()
  308. if marker in (mmarkers.TICKUP, '|'):
  309. trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)
  310. elif marker == mmarkers.TICKDOWN:
  311. trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)
  312. else:
  313. # Don't modify custom tick line markers.
  314. trans = self.tick1line._marker._transform
  315. self.tick1line._marker._transform = trans
  316. marker = self.tick2line.get_marker()
  317. if marker in (mmarkers.TICKUP, '|'):
  318. trans = mtransforms.Affine2D().scale(1, 1).rotate(angle)
  319. elif marker == mmarkers.TICKDOWN:
  320. trans = mtransforms.Affine2D().scale(1, -1).rotate(angle)
  321. else:
  322. # Don't modify custom tick line markers.
  323. trans = self.tick2line._marker._transform
  324. self.tick2line._marker._transform = trans
  325. mode, user_angle = self._labelrotation
  326. if mode == 'default':
  327. text_angle = user_angle
  328. else:
  329. if text_angle > 90:
  330. text_angle -= 180
  331. elif text_angle < -90:
  332. text_angle += 180
  333. text_angle += user_angle
  334. self.label1.set_rotation(text_angle)
  335. self.label2.set_rotation(text_angle)
  336. # This extra padding helps preserve the look from previous releases but
  337. # is also needed because labels are anchored to their center.
  338. pad = self._pad + 7
  339. self._update_padding(pad,
  340. self._loc * axes.get_theta_direction() +
  341. axes.get_theta_offset())
  342. class ThetaAxis(maxis.XAxis):
  343. """
  344. A theta Axis.
  345. This overrides certain properties of an `.XAxis` to provide special-casing
  346. for an angular axis.
  347. """
  348. __name__ = 'thetaaxis'
  349. axis_name = 'theta' #: Read-only name identifying the axis.
  350. _tick_class = ThetaTick
  351. def _wrap_locator_formatter(self):
  352. self.set_major_locator(ThetaLocator(self.get_major_locator()))
  353. self.set_major_formatter(ThetaFormatter())
  354. self.isDefault_majloc = True
  355. self.isDefault_majfmt = True
  356. def clear(self):
  357. # docstring inherited
  358. super().clear()
  359. self.set_ticks_position('none')
  360. self._wrap_locator_formatter()
  361. def _set_scale(self, value, **kwargs):
  362. if value != 'linear':
  363. raise NotImplementedError(
  364. "The xscale cannot be set on a polar plot")
  365. super()._set_scale(value, **kwargs)
  366. # LinearScale.set_default_locators_and_formatters just set the major
  367. # locator to be an AutoLocator, so we customize it here to have ticks
  368. # at sensible degree multiples.
  369. self.get_major_locator().set_params(steps=[1, 1.5, 3, 4.5, 9, 10])
  370. self._wrap_locator_formatter()
  371. def _copy_tick_props(self, src, dest):
  372. """Copy the props from src tick to dest tick."""
  373. if src is None or dest is None:
  374. return
  375. super()._copy_tick_props(src, dest)
  376. # Ensure that tick transforms are independent so that padding works.
  377. trans = dest._get_text1_transform()[0]
  378. dest.label1.set_transform(trans + dest._text1_translate)
  379. trans = dest._get_text2_transform()[0]
  380. dest.label2.set_transform(trans + dest._text2_translate)
  381. class RadialLocator(mticker.Locator):
  382. """
  383. Used to locate radius ticks.
  384. Ensures that all ticks are strictly positive. For all other tasks, it
  385. delegates to the base `.Locator` (which may be different depending on the
  386. scale of the *r*-axis).
  387. """
  388. def __init__(self, base, axes=None):
  389. self.base = base
  390. self._axes = axes
  391. def set_axis(self, axis):
  392. self.base.set_axis(axis)
  393. def __call__(self):
  394. # Ensure previous behaviour with full circle non-annular views.
  395. if self._axes:
  396. if _is_full_circle_rad(*self._axes.viewLim.intervalx):
  397. rorigin = self._axes.get_rorigin() * self._axes.get_rsign()
  398. if self._axes.get_rmin() <= rorigin:
  399. return [tick for tick in self.base() if tick > rorigin]
  400. return self.base()
  401. def _zero_in_bounds(self):
  402. """
  403. Return True if zero is within the valid values for the
  404. scale of the radial axis.
  405. """
  406. vmin, vmax = self._axes.yaxis._scale.limit_range_for_scale(0, 1, 1e-5)
  407. return vmin == 0
  408. def nonsingular(self, vmin, vmax):
  409. # docstring inherited
  410. if self._zero_in_bounds() and (vmin, vmax) == (-np.inf, np.inf):
  411. # Initial view limits
  412. return (0, 1)
  413. else:
  414. return self.base.nonsingular(vmin, vmax)
  415. def view_limits(self, vmin, vmax):
  416. vmin, vmax = self.base.view_limits(vmin, vmax)
  417. if self._zero_in_bounds() and vmax > vmin:
  418. # this allows inverted r/y-lims
  419. vmin = min(0, vmin)
  420. return mtransforms.nonsingular(vmin, vmax)
  421. class _ThetaShift(mtransforms.ScaledTranslation):
  422. """
  423. Apply a padding shift based on axes theta limits.
  424. This is used to create padding for radial ticks.
  425. Parameters
  426. ----------
  427. axes : `~matplotlib.axes.Axes`
  428. The owning axes; used to determine limits.
  429. pad : float
  430. The padding to apply, in points.
  431. mode : {'min', 'max', 'rlabel'}
  432. Whether to shift away from the start (``'min'``) or the end (``'max'``)
  433. of the axes, or using the rlabel position (``'rlabel'``).
  434. """
  435. def __init__(self, axes, pad, mode):
  436. super().__init__(pad, pad, axes.figure.dpi_scale_trans)
  437. self.set_children(axes._realViewLim)
  438. self.axes = axes
  439. self.mode = mode
  440. self.pad = pad
  441. __str__ = mtransforms._make_str_method("axes", "pad", "mode")
  442. def get_matrix(self):
  443. if self._invalid:
  444. if self.mode == 'rlabel':
  445. angle = (
  446. np.deg2rad(self.axes.get_rlabel_position()) *
  447. self.axes.get_theta_direction() +
  448. self.axes.get_theta_offset()
  449. )
  450. else:
  451. if self.mode == 'min':
  452. angle = self.axes._realViewLim.xmin
  453. elif self.mode == 'max':
  454. angle = self.axes._realViewLim.xmax
  455. if self.mode in ('rlabel', 'min'):
  456. padx = np.cos(angle - np.pi / 2)
  457. pady = np.sin(angle - np.pi / 2)
  458. else:
  459. padx = np.cos(angle + np.pi / 2)
  460. pady = np.sin(angle + np.pi / 2)
  461. self._t = (self.pad * padx / 72, self.pad * pady / 72)
  462. return super().get_matrix()
  463. class RadialTick(maxis.YTick):
  464. """
  465. A radial-axis tick.
  466. This subclass of `.YTick` provides radial ticks with some small
  467. modification to their re-positioning such that ticks are rotated based on
  468. axes limits. This results in ticks that are correctly perpendicular to
  469. the spine. Labels are also rotated to be perpendicular to the spine, when
  470. 'auto' rotation is enabled.
  471. """
  472. def __init__(self, *args, **kwargs):
  473. super().__init__(*args, **kwargs)
  474. self.label1.set_rotation_mode('anchor')
  475. self.label2.set_rotation_mode('anchor')
  476. def _determine_anchor(self, mode, angle, start):
  477. # Note: angle is the (spine angle - 90) because it's used for the tick
  478. # & text setup, so all numbers below are -90 from (normed) spine angle.
  479. if mode == 'auto':
  480. if start:
  481. if -90 <= angle <= 90:
  482. return 'left', 'center'
  483. else:
  484. return 'right', 'center'
  485. else:
  486. if -90 <= angle <= 90:
  487. return 'right', 'center'
  488. else:
  489. return 'left', 'center'
  490. else:
  491. if start:
  492. if angle < -68.5:
  493. return 'center', 'top'
  494. elif angle < -23.5:
  495. return 'left', 'top'
  496. elif angle < 22.5:
  497. return 'left', 'center'
  498. elif angle < 67.5:
  499. return 'left', 'bottom'
  500. elif angle < 112.5:
  501. return 'center', 'bottom'
  502. elif angle < 157.5:
  503. return 'right', 'bottom'
  504. elif angle < 202.5:
  505. return 'right', 'center'
  506. elif angle < 247.5:
  507. return 'right', 'top'
  508. else:
  509. return 'center', 'top'
  510. else:
  511. if angle < -68.5:
  512. return 'center', 'bottom'
  513. elif angle < -23.5:
  514. return 'right', 'bottom'
  515. elif angle < 22.5:
  516. return 'right', 'center'
  517. elif angle < 67.5:
  518. return 'right', 'top'
  519. elif angle < 112.5:
  520. return 'center', 'top'
  521. elif angle < 157.5:
  522. return 'left', 'top'
  523. elif angle < 202.5:
  524. return 'left', 'center'
  525. elif angle < 247.5:
  526. return 'left', 'bottom'
  527. else:
  528. return 'center', 'bottom'
  529. def update_position(self, loc):
  530. super().update_position(loc)
  531. axes = self.axes
  532. thetamin = axes.get_thetamin()
  533. thetamax = axes.get_thetamax()
  534. direction = axes.get_theta_direction()
  535. offset_rad = axes.get_theta_offset()
  536. offset = np.rad2deg(offset_rad)
  537. full = _is_full_circle_deg(thetamin, thetamax)
  538. if full:
  539. angle = (axes.get_rlabel_position() * direction +
  540. offset) % 360 - 90
  541. tick_angle = 0
  542. else:
  543. angle = (thetamin * direction + offset) % 360 - 90
  544. if direction > 0:
  545. tick_angle = np.deg2rad(angle)
  546. else:
  547. tick_angle = np.deg2rad(angle + 180)
  548. text_angle = (angle + 90) % 180 - 90 # between -90 and +90.
  549. mode, user_angle = self._labelrotation
  550. if mode == 'auto':
  551. text_angle += user_angle
  552. else:
  553. text_angle = user_angle
  554. if full:
  555. ha = self.label1.get_horizontalalignment()
  556. va = self.label1.get_verticalalignment()
  557. else:
  558. ha, va = self._determine_anchor(mode, angle, direction > 0)
  559. self.label1.set_horizontalalignment(ha)
  560. self.label1.set_verticalalignment(va)
  561. self.label1.set_rotation(text_angle)
  562. marker = self.tick1line.get_marker()
  563. if marker == mmarkers.TICKLEFT:
  564. trans = mtransforms.Affine2D().rotate(tick_angle)
  565. elif marker == '_':
  566. trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
  567. elif marker == mmarkers.TICKRIGHT:
  568. trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
  569. else:
  570. # Don't modify custom tick line markers.
  571. trans = self.tick1line._marker._transform
  572. self.tick1line._marker._transform = trans
  573. if full:
  574. self.label2.set_visible(False)
  575. self.tick2line.set_visible(False)
  576. angle = (thetamax * direction + offset) % 360 - 90
  577. if direction > 0:
  578. tick_angle = np.deg2rad(angle)
  579. else:
  580. tick_angle = np.deg2rad(angle + 180)
  581. text_angle = (angle + 90) % 180 - 90 # between -90 and +90.
  582. mode, user_angle = self._labelrotation
  583. if mode == 'auto':
  584. text_angle += user_angle
  585. else:
  586. text_angle = user_angle
  587. ha, va = self._determine_anchor(mode, angle, direction < 0)
  588. self.label2.set_ha(ha)
  589. self.label2.set_va(va)
  590. self.label2.set_rotation(text_angle)
  591. marker = self.tick2line.get_marker()
  592. if marker == mmarkers.TICKLEFT:
  593. trans = mtransforms.Affine2D().rotate(tick_angle)
  594. elif marker == '_':
  595. trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2)
  596. elif marker == mmarkers.TICKRIGHT:
  597. trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle)
  598. else:
  599. # Don't modify custom tick line markers.
  600. trans = self.tick2line._marker._transform
  601. self.tick2line._marker._transform = trans
  602. class RadialAxis(maxis.YAxis):
  603. """
  604. A radial Axis.
  605. This overrides certain properties of a `.YAxis` to provide special-casing
  606. for a radial axis.
  607. """
  608. __name__ = 'radialaxis'
  609. axis_name = 'radius' #: Read-only name identifying the axis.
  610. _tick_class = RadialTick
  611. def __init__(self, *args, **kwargs):
  612. super().__init__(*args, **kwargs)
  613. self.sticky_edges.y.append(0)
  614. def _wrap_locator_formatter(self):
  615. self.set_major_locator(RadialLocator(self.get_major_locator(),
  616. self.axes))
  617. self.isDefault_majloc = True
  618. def clear(self):
  619. # docstring inherited
  620. super().clear()
  621. self.set_ticks_position('none')
  622. self._wrap_locator_formatter()
  623. def _set_scale(self, value, **kwargs):
  624. super()._set_scale(value, **kwargs)
  625. self._wrap_locator_formatter()
  626. def _is_full_circle_deg(thetamin, thetamax):
  627. """
  628. Determine if a wedge (in degrees) spans the full circle.
  629. The condition is derived from :class:`~matplotlib.patches.Wedge`.
  630. """
  631. return abs(abs(thetamax - thetamin) - 360.0) < 1e-12
  632. def _is_full_circle_rad(thetamin, thetamax):
  633. """
  634. Determine if a wedge (in radians) spans the full circle.
  635. The condition is derived from :class:`~matplotlib.patches.Wedge`.
  636. """
  637. return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14
  638. class _WedgeBbox(mtransforms.Bbox):
  639. """
  640. Transform (theta, r) wedge Bbox into axes bounding box.
  641. Parameters
  642. ----------
  643. center : (float, float)
  644. Center of the wedge
  645. viewLim : `~matplotlib.transforms.Bbox`
  646. Bbox determining the boundaries of the wedge
  647. originLim : `~matplotlib.transforms.Bbox`
  648. Bbox determining the origin for the wedge, if different from *viewLim*
  649. """
  650. def __init__(self, center, viewLim, originLim, **kwargs):
  651. super().__init__([[0, 0], [1, 1]], **kwargs)
  652. self._center = center
  653. self._viewLim = viewLim
  654. self._originLim = originLim
  655. self.set_children(viewLim, originLim)
  656. __str__ = mtransforms._make_str_method("_center", "_viewLim", "_originLim")
  657. def get_points(self):
  658. # docstring inherited
  659. if self._invalid:
  660. points = self._viewLim.get_points().copy()
  661. # Scale angular limits to work with Wedge.
  662. points[:, 0] *= 180 / np.pi
  663. if points[0, 0] > points[1, 0]:
  664. points[:, 0] = points[::-1, 0]
  665. # Scale radial limits based on origin radius.
  666. points[:, 1] -= self._originLim.y0
  667. # Scale radial limits to match axes limits.
  668. rscale = 0.5 / points[1, 1]
  669. points[:, 1] *= rscale
  670. width = min(points[1, 1] - points[0, 1], 0.5)
  671. # Generate bounding box for wedge.
  672. wedge = mpatches.Wedge(self._center, points[1, 1],
  673. points[0, 0], points[1, 0],
  674. width=width)
  675. self.update_from_path(wedge.get_path())
  676. # Ensure equal aspect ratio.
  677. w, h = self._points[1] - self._points[0]
  678. deltah = max(w - h, 0) / 2
  679. deltaw = max(h - w, 0) / 2
  680. self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]])
  681. self._invalid = 0
  682. return self._points
  683. class PolarAxes(Axes):
  684. """
  685. A polar graph projection, where the input dimensions are *theta*, *r*.
  686. Theta starts pointing east and goes anti-clockwise.
  687. """
  688. name = 'polar'
  689. def __init__(self, *args,
  690. theta_offset=0, theta_direction=1, rlabel_position=22.5,
  691. **kwargs):
  692. # docstring inherited
  693. self._default_theta_offset = theta_offset
  694. self._default_theta_direction = theta_direction
  695. self._default_rlabel_position = np.deg2rad(rlabel_position)
  696. super().__init__(*args, **kwargs)
  697. self.use_sticky_edges = True
  698. self.set_aspect('equal', adjustable='box', anchor='C')
  699. self.clear()
  700. def clear(self):
  701. # docstring inherited
  702. super().clear()
  703. self.title.set_y(1.05)
  704. start = self.spines.get('start', None)
  705. if start:
  706. start.set_visible(False)
  707. end = self.spines.get('end', None)
  708. if end:
  709. end.set_visible(False)
  710. self.set_xlim(0.0, 2 * np.pi)
  711. self.grid(mpl.rcParams['polaraxes.grid'])
  712. inner = self.spines.get('inner', None)
  713. if inner:
  714. inner.set_visible(False)
  715. self.set_rorigin(None)
  716. self.set_theta_offset(self._default_theta_offset)
  717. self.set_theta_direction(self._default_theta_direction)
  718. def _init_axis(self):
  719. # This is moved out of __init__ because non-separable axes don't use it
  720. self.xaxis = ThetaAxis(self, clear=False)
  721. self.yaxis = RadialAxis(self, clear=False)
  722. self.spines['polar'].register_axis(self.yaxis)
  723. def _set_lim_and_transforms(self):
  724. # A view limit where the minimum radius can be locked if the user
  725. # specifies an alternate origin.
  726. self._originViewLim = mtransforms.LockableBbox(self.viewLim)
  727. # Handle angular offset and direction.
  728. self._direction = mtransforms.Affine2D() \
  729. .scale(self._default_theta_direction, 1.0)
  730. self._theta_offset = mtransforms.Affine2D() \
  731. .translate(self._default_theta_offset, 0.0)
  732. self.transShift = self._direction + self._theta_offset
  733. # A view limit shifted to the correct location after accounting for
  734. # orientation and offset.
  735. self._realViewLim = mtransforms.TransformedBbox(self.viewLim,
  736. self.transShift)
  737. # Transforms the x and y axis separately by a scale factor
  738. # It is assumed that this part will have non-linear components
  739. self.transScale = mtransforms.TransformWrapper(
  740. mtransforms.IdentityTransform())
  741. # Scale view limit into a bbox around the selected wedge. This may be
  742. # smaller than the usual unit axes rectangle if not plotting the full
  743. # circle.
  744. self.axesLim = _WedgeBbox((0.5, 0.5),
  745. self._realViewLim, self._originViewLim)
  746. # Scale the wedge to fill the axes.
  747. self.transWedge = mtransforms.BboxTransformFrom(self.axesLim)
  748. # Scale the axes to fill the figure.
  749. self.transAxes = mtransforms.BboxTransformTo(self.bbox)
  750. # A (possibly non-linear) projection on the (already scaled)
  751. # data. This one is aware of rmin
  752. self.transProjection = self.PolarTransform(
  753. self,
  754. _apply_theta_transforms=False,
  755. scale_transform=self.transScale
  756. )
  757. # Add dependency on rorigin.
  758. self.transProjection.set_children(self._originViewLim)
  759. # An affine transformation on the data, generally to limit the
  760. # range of the axes
  761. self.transProjectionAffine = self.PolarAffine(self.transScale,
  762. self._originViewLim)
  763. # The complete data transformation stack -- from data all the
  764. # way to display coordinates
  765. #
  766. # 1. Remove any radial axis scaling (e.g. log scaling)
  767. # 2. Shift data in the theta direction
  768. # 3. Project the data from polar to cartesian values
  769. # (with the origin in the same place)
  770. # 4. Scale and translate the cartesian values to Axes coordinates
  771. # (here the origin is moved to the lower left of the Axes)
  772. # 5. Move and scale to fill the Axes
  773. # 6. Convert from Axes coordinates to Figure coordinates
  774. self.transData = (
  775. self.transScale +
  776. self.transShift +
  777. self.transProjection +
  778. (
  779. self.transProjectionAffine +
  780. self.transWedge +
  781. self.transAxes
  782. )
  783. )
  784. # This is the transform for theta-axis ticks. It is
  785. # equivalent to transData, except it always puts r == 0.0 and r == 1.0
  786. # at the edge of the axis circles.
  787. self._xaxis_transform = (
  788. mtransforms.blended_transform_factory(
  789. mtransforms.IdentityTransform(),
  790. mtransforms.BboxTransformTo(self.viewLim)) +
  791. self.transData)
  792. # The theta labels are flipped along the radius, so that text 1 is on
  793. # the outside by default. This should work the same as before.
  794. flipr_transform = mtransforms.Affine2D() \
  795. .translate(0.0, -0.5) \
  796. .scale(1.0, -1.0) \
  797. .translate(0.0, 0.5)
  798. self._xaxis_text_transform = flipr_transform + self._xaxis_transform
  799. # This is the transform for r-axis ticks. It scales the theta
  800. # axis so the gridlines from 0.0 to 1.0, now go from thetamin to
  801. # thetamax.
  802. self._yaxis_transform = (
  803. mtransforms.blended_transform_factory(
  804. mtransforms.BboxTransformTo(self.viewLim),
  805. mtransforms.IdentityTransform()) +
  806. self.transData)
  807. # The r-axis labels are put at an angle and padded in the r-direction
  808. self._r_label_position = mtransforms.Affine2D() \
  809. .translate(self._default_rlabel_position, 0.0)
  810. self._yaxis_text_transform = mtransforms.TransformWrapper(
  811. self._r_label_position + self.transData)
  812. def get_xaxis_transform(self, which='grid'):
  813. _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)
  814. return self._xaxis_transform
  815. def get_xaxis_text1_transform(self, pad):
  816. return self._xaxis_text_transform, 'center', 'center'
  817. def get_xaxis_text2_transform(self, pad):
  818. return self._xaxis_text_transform, 'center', 'center'
  819. def get_yaxis_transform(self, which='grid'):
  820. if which in ('tick1', 'tick2'):
  821. return self._yaxis_text_transform
  822. elif which == 'grid':
  823. return self._yaxis_transform
  824. else:
  825. _api.check_in_list(['tick1', 'tick2', 'grid'], which=which)
  826. def get_yaxis_text1_transform(self, pad):
  827. thetamin, thetamax = self._realViewLim.intervalx
  828. if _is_full_circle_rad(thetamin, thetamax):
  829. return self._yaxis_text_transform, 'bottom', 'left'
  830. elif self.get_theta_direction() > 0:
  831. halign = 'left'
  832. pad_shift = _ThetaShift(self, pad, 'min')
  833. else:
  834. halign = 'right'
  835. pad_shift = _ThetaShift(self, pad, 'max')
  836. return self._yaxis_text_transform + pad_shift, 'center', halign
  837. def get_yaxis_text2_transform(self, pad):
  838. if self.get_theta_direction() > 0:
  839. halign = 'right'
  840. pad_shift = _ThetaShift(self, pad, 'max')
  841. else:
  842. halign = 'left'
  843. pad_shift = _ThetaShift(self, pad, 'min')
  844. return self._yaxis_text_transform + pad_shift, 'center', halign
  845. def draw(self, renderer):
  846. self._unstale_viewLim()
  847. thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
  848. if thetamin > thetamax:
  849. thetamin, thetamax = thetamax, thetamin
  850. rmin, rmax = ((self._realViewLim.intervaly - self.get_rorigin()) *
  851. self.get_rsign())
  852. if isinstance(self.patch, mpatches.Wedge):
  853. # Backwards-compatibility: Any subclassed Axes might override the
  854. # patch to not be the Wedge that PolarAxes uses.
  855. center = self.transWedge.transform((0.5, 0.5))
  856. self.patch.set_center(center)
  857. self.patch.set_theta1(thetamin)
  858. self.patch.set_theta2(thetamax)
  859. edge, _ = self.transWedge.transform((1, 0))
  860. radius = edge - center[0]
  861. width = min(radius * (rmax - rmin) / rmax, radius)
  862. self.patch.set_radius(radius)
  863. self.patch.set_width(width)
  864. inner_width = radius - width
  865. inner = self.spines.get('inner', None)
  866. if inner:
  867. inner.set_visible(inner_width != 0.0)
  868. visible = not _is_full_circle_deg(thetamin, thetamax)
  869. # For backwards compatibility, any subclassed Axes might override the
  870. # spines to not include start/end that PolarAxes uses.
  871. start = self.spines.get('start', None)
  872. end = self.spines.get('end', None)
  873. if start:
  874. start.set_visible(visible)
  875. if end:
  876. end.set_visible(visible)
  877. if visible:
  878. yaxis_text_transform = self._yaxis_transform
  879. else:
  880. yaxis_text_transform = self._r_label_position + self.transData
  881. if self._yaxis_text_transform != yaxis_text_transform:
  882. self._yaxis_text_transform.set(yaxis_text_transform)
  883. self.yaxis.reset_ticks()
  884. self.yaxis.set_clip_path(self.patch)
  885. super().draw(renderer)
  886. def _gen_axes_patch(self):
  887. return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0)
  888. def _gen_axes_spines(self):
  889. spines = {
  890. 'polar': Spine.arc_spine(self, 'top', (0.5, 0.5), 0.5, 0, 360),
  891. 'start': Spine.linear_spine(self, 'left'),
  892. 'end': Spine.linear_spine(self, 'right'),
  893. 'inner': Spine.arc_spine(self, 'bottom', (0.5, 0.5), 0.0, 0, 360),
  894. }
  895. spines['polar'].set_transform(self.transWedge + self.transAxes)
  896. spines['inner'].set_transform(self.transWedge + self.transAxes)
  897. spines['start'].set_transform(self._yaxis_transform)
  898. spines['end'].set_transform(self._yaxis_transform)
  899. return spines
  900. def set_thetamax(self, thetamax):
  901. """Set the maximum theta limit in degrees."""
  902. self.viewLim.x1 = np.deg2rad(thetamax)
  903. def get_thetamax(self):
  904. """Return the maximum theta limit in degrees."""
  905. return np.rad2deg(self.viewLim.xmax)
  906. def set_thetamin(self, thetamin):
  907. """Set the minimum theta limit in degrees."""
  908. self.viewLim.x0 = np.deg2rad(thetamin)
  909. def get_thetamin(self):
  910. """Get the minimum theta limit in degrees."""
  911. return np.rad2deg(self.viewLim.xmin)
  912. def set_thetalim(self, *args, **kwargs):
  913. r"""
  914. Set the minimum and maximum theta values.
  915. Can take the following signatures:
  916. - ``set_thetalim(minval, maxval)``: Set the limits in radians.
  917. - ``set_thetalim(thetamin=minval, thetamax=maxval)``: Set the limits
  918. in degrees.
  919. where minval and maxval are the minimum and maximum limits. Values are
  920. wrapped in to the range :math:`[0, 2\pi]` (in radians), so for example
  921. it is possible to do ``set_thetalim(-np.pi / 2, np.pi / 2)`` to have
  922. an axis symmetric around 0. A ValueError is raised if the absolute
  923. angle difference is larger than a full circle.
  924. """
  925. orig_lim = self.get_xlim() # in radians
  926. if 'thetamin' in kwargs:
  927. kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin'))
  928. if 'thetamax' in kwargs:
  929. kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax'))
  930. new_min, new_max = self.set_xlim(*args, **kwargs)
  931. # Parsing all permutations of *args, **kwargs is tricky; it is simpler
  932. # to let set_xlim() do it and then validate the limits.
  933. if abs(new_max - new_min) > 2 * np.pi:
  934. self.set_xlim(orig_lim) # un-accept the change
  935. raise ValueError("The angle range must be less than a full circle")
  936. return tuple(np.rad2deg((new_min, new_max)))
  937. def set_theta_offset(self, offset):
  938. """
  939. Set the offset for the location of 0 in radians.
  940. """
  941. mtx = self._theta_offset.get_matrix()
  942. mtx[0, 2] = offset
  943. self._theta_offset.invalidate()
  944. def get_theta_offset(self):
  945. """
  946. Get the offset for the location of 0 in radians.
  947. """
  948. return self._theta_offset.get_matrix()[0, 2]
  949. def set_theta_zero_location(self, loc, offset=0.0):
  950. """
  951. Set the location of theta's zero.
  952. This simply calls `set_theta_offset` with the correct value in radians.
  953. Parameters
  954. ----------
  955. loc : str
  956. May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE".
  957. offset : float, default: 0
  958. An offset in degrees to apply from the specified *loc*. **Note:**
  959. this offset is *always* applied counter-clockwise regardless of
  960. the direction setting.
  961. """
  962. mapping = {
  963. 'N': np.pi * 0.5,
  964. 'NW': np.pi * 0.75,
  965. 'W': np.pi,
  966. 'SW': np.pi * 1.25,
  967. 'S': np.pi * 1.5,
  968. 'SE': np.pi * 1.75,
  969. 'E': 0,
  970. 'NE': np.pi * 0.25}
  971. return self.set_theta_offset(mapping[loc] + np.deg2rad(offset))
  972. def set_theta_direction(self, direction):
  973. """
  974. Set the direction in which theta increases.
  975. clockwise, -1:
  976. Theta increases in the clockwise direction
  977. counterclockwise, anticlockwise, 1:
  978. Theta increases in the counterclockwise direction
  979. """
  980. mtx = self._direction.get_matrix()
  981. if direction in ('clockwise', -1):
  982. mtx[0, 0] = -1
  983. elif direction in ('counterclockwise', 'anticlockwise', 1):
  984. mtx[0, 0] = 1
  985. else:
  986. _api.check_in_list(
  987. [-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'],
  988. direction=direction)
  989. self._direction.invalidate()
  990. def get_theta_direction(self):
  991. """
  992. Get the direction in which theta increases.
  993. -1:
  994. Theta increases in the clockwise direction
  995. 1:
  996. Theta increases in the counterclockwise direction
  997. """
  998. return self._direction.get_matrix()[0, 0]
  999. def set_rmax(self, rmax):
  1000. """
  1001. Set the outer radial limit.
  1002. Parameters
  1003. ----------
  1004. rmax : float
  1005. """
  1006. self.viewLim.y1 = rmax
  1007. def get_rmax(self):
  1008. """
  1009. Returns
  1010. -------
  1011. float
  1012. Outer radial limit.
  1013. """
  1014. return self.viewLim.ymax
  1015. def set_rmin(self, rmin):
  1016. """
  1017. Set the inner radial limit.
  1018. Parameters
  1019. ----------
  1020. rmin : float
  1021. """
  1022. self.viewLim.y0 = rmin
  1023. def get_rmin(self):
  1024. """
  1025. Returns
  1026. -------
  1027. float
  1028. The inner radial limit.
  1029. """
  1030. return self.viewLim.ymin
  1031. def set_rorigin(self, rorigin):
  1032. """
  1033. Update the radial origin.
  1034. Parameters
  1035. ----------
  1036. rorigin : float
  1037. """
  1038. self._originViewLim.locked_y0 = rorigin
  1039. def get_rorigin(self):
  1040. """
  1041. Returns
  1042. -------
  1043. float
  1044. """
  1045. return self._originViewLim.y0
  1046. def get_rsign(self):
  1047. return np.sign(self._originViewLim.y1 - self._originViewLim.y0)
  1048. def set_rlim(self, bottom=None, top=None, *,
  1049. emit=True, auto=False, **kwargs):
  1050. """
  1051. Set the radial axis view limits.
  1052. This function behaves like `.Axes.set_ylim`, but additionally supports
  1053. *rmin* and *rmax* as aliases for *bottom* and *top*.
  1054. See Also
  1055. --------
  1056. .Axes.set_ylim
  1057. """
  1058. if 'rmin' in kwargs:
  1059. if bottom is None:
  1060. bottom = kwargs.pop('rmin')
  1061. else:
  1062. raise ValueError('Cannot supply both positional "bottom"'
  1063. 'argument and kwarg "rmin"')
  1064. if 'rmax' in kwargs:
  1065. if top is None:
  1066. top = kwargs.pop('rmax')
  1067. else:
  1068. raise ValueError('Cannot supply both positional "top"'
  1069. 'argument and kwarg "rmax"')
  1070. return self.set_ylim(bottom=bottom, top=top, emit=emit, auto=auto,
  1071. **kwargs)
  1072. def get_rlabel_position(self):
  1073. """
  1074. Returns
  1075. -------
  1076. float
  1077. The theta position of the radius labels in degrees.
  1078. """
  1079. return np.rad2deg(self._r_label_position.get_matrix()[0, 2])
  1080. def set_rlabel_position(self, value):
  1081. """
  1082. Update the theta position of the radius labels.
  1083. Parameters
  1084. ----------
  1085. value : number
  1086. The angular position of the radius labels in degrees.
  1087. """
  1088. self._r_label_position.clear().translate(np.deg2rad(value), 0.0)
  1089. def set_yscale(self, *args, **kwargs):
  1090. super().set_yscale(*args, **kwargs)
  1091. self.yaxis.set_major_locator(
  1092. self.RadialLocator(self.yaxis.get_major_locator(), self))
  1093. def set_rscale(self, *args, **kwargs):
  1094. return Axes.set_yscale(self, *args, **kwargs)
  1095. def set_rticks(self, *args, **kwargs):
  1096. return Axes.set_yticks(self, *args, **kwargs)
  1097. def set_thetagrids(self, angles, labels=None, fmt=None, **kwargs):
  1098. """
  1099. Set the theta gridlines in a polar plot.
  1100. Parameters
  1101. ----------
  1102. angles : tuple with floats, degrees
  1103. The angles of the theta gridlines.
  1104. labels : tuple with strings or None
  1105. The labels to use at each theta gridline. The
  1106. `.projections.polar.ThetaFormatter` will be used if None.
  1107. fmt : str or None
  1108. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1109. For example '%f'. Note that the angle that is used is in
  1110. radians.
  1111. Returns
  1112. -------
  1113. lines : list of `.lines.Line2D`
  1114. The theta gridlines.
  1115. labels : list of `.text.Text`
  1116. The tick labels.
  1117. Other Parameters
  1118. ----------------
  1119. **kwargs
  1120. *kwargs* are optional `.Text` properties for the labels.
  1121. .. warning::
  1122. This only sets the properties of the current ticks.
  1123. Ticks are not guaranteed to be persistent. Various operations
  1124. can create, delete and modify the Tick instances. There is an
  1125. imminent risk that these settings can get lost if you work on
  1126. the figure further (including also panning/zooming on a
  1127. displayed figure).
  1128. Use `.set_tick_params` instead if possible.
  1129. See Also
  1130. --------
  1131. .PolarAxes.set_rgrids
  1132. .Axis.get_gridlines
  1133. .Axis.get_ticklabels
  1134. """
  1135. # Make sure we take into account unitized data
  1136. angles = self.convert_yunits(angles)
  1137. angles = np.deg2rad(angles)
  1138. self.set_xticks(angles)
  1139. if labels is not None:
  1140. self.set_xticklabels(labels)
  1141. elif fmt is not None:
  1142. self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))
  1143. for t in self.xaxis.get_ticklabels():
  1144. t._internal_update(kwargs)
  1145. return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()
  1146. def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs):
  1147. """
  1148. Set the radial gridlines on a polar plot.
  1149. Parameters
  1150. ----------
  1151. radii : tuple with floats
  1152. The radii for the radial gridlines
  1153. labels : tuple with strings or None
  1154. The labels to use at each radial gridline. The
  1155. `matplotlib.ticker.ScalarFormatter` will be used if None.
  1156. angle : float
  1157. The angular position of the radius labels in degrees.
  1158. fmt : str or None
  1159. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1160. For example '%f'.
  1161. Returns
  1162. -------
  1163. lines : list of `.lines.Line2D`
  1164. The radial gridlines.
  1165. labels : list of `.text.Text`
  1166. The tick labels.
  1167. Other Parameters
  1168. ----------------
  1169. **kwargs
  1170. *kwargs* are optional `.Text` properties for the labels.
  1171. .. warning::
  1172. This only sets the properties of the current ticks.
  1173. Ticks are not guaranteed to be persistent. Various operations
  1174. can create, delete and modify the Tick instances. There is an
  1175. imminent risk that these settings can get lost if you work on
  1176. the figure further (including also panning/zooming on a
  1177. displayed figure).
  1178. Use `.set_tick_params` instead if possible.
  1179. See Also
  1180. --------
  1181. .PolarAxes.set_thetagrids
  1182. .Axis.get_gridlines
  1183. .Axis.get_ticklabels
  1184. """
  1185. # Make sure we take into account unitized data
  1186. radii = self.convert_xunits(radii)
  1187. radii = np.asarray(radii)
  1188. self.set_yticks(radii)
  1189. if labels is not None:
  1190. self.set_yticklabels(labels)
  1191. elif fmt is not None:
  1192. self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))
  1193. if angle is None:
  1194. angle = self.get_rlabel_position()
  1195. self.set_rlabel_position(angle)
  1196. for t in self.yaxis.get_ticklabels():
  1197. t._internal_update(kwargs)
  1198. return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()
  1199. def format_coord(self, theta, r):
  1200. # docstring inherited
  1201. screen_xy = self.transData.transform((theta, r))
  1202. screen_xys = screen_xy + np.stack(
  1203. np.meshgrid([-1, 0, 1], [-1, 0, 1])).reshape((2, -1)).T
  1204. ts, rs = self.transData.inverted().transform(screen_xys).T
  1205. delta_t = abs((ts - theta + np.pi) % (2 * np.pi) - np.pi).max()
  1206. delta_t_halfturns = delta_t / np.pi
  1207. delta_t_degrees = delta_t_halfturns * 180
  1208. delta_r = abs(rs - r).max()
  1209. if theta < 0:
  1210. theta += 2 * np.pi
  1211. theta_halfturns = theta / np.pi
  1212. theta_degrees = theta_halfturns * 180
  1213. # See ScalarFormatter.format_data_short. For r, use #g-formatting
  1214. # (as for linear axes), but for theta, use f-formatting as scientific
  1215. # notation doesn't make sense and the trailing dot is ugly.
  1216. def format_sig(value, delta, opt, fmt):
  1217. # For "f", only count digits after decimal point.
  1218. prec = (max(0, -math.floor(math.log10(delta))) if fmt == "f" else
  1219. cbook._g_sig_digits(value, delta))
  1220. return f"{value:-{opt}.{prec}{fmt}}"
  1221. return ('\N{GREEK SMALL LETTER THETA}={}\N{GREEK SMALL LETTER PI} '
  1222. '({}\N{DEGREE SIGN}), r={}').format(
  1223. format_sig(theta_halfturns, delta_t_halfturns, "", "f"),
  1224. format_sig(theta_degrees, delta_t_degrees, "", "f"),
  1225. format_sig(r, delta_r, "#", "g"),
  1226. )
  1227. def get_data_ratio(self):
  1228. """
  1229. Return the aspect ratio of the data itself. For a polar plot,
  1230. this should always be 1.0
  1231. """
  1232. return 1.0
  1233. # # # Interactive panning
  1234. def can_zoom(self):
  1235. """
  1236. Return whether this Axes supports the zoom box button functionality.
  1237. A polar Axes does not support zoom boxes.
  1238. """
  1239. return False
  1240. def can_pan(self):
  1241. """
  1242. Return whether this Axes supports the pan/zoom button functionality.
  1243. For a polar Axes, this is slightly misleading. Both panning and
  1244. zooming are performed by the same button. Panning is performed
  1245. in azimuth while zooming is done along the radial.
  1246. """
  1247. return True
  1248. def start_pan(self, x, y, button):
  1249. angle = np.deg2rad(self.get_rlabel_position())
  1250. mode = ''
  1251. if button == 1:
  1252. epsilon = np.pi / 45.0
  1253. t, r = self.transData.inverted().transform((x, y))
  1254. if angle - epsilon <= t <= angle + epsilon:
  1255. mode = 'drag_r_labels'
  1256. elif button == 3:
  1257. mode = 'zoom'
  1258. self._pan_start = types.SimpleNamespace(
  1259. rmax=self.get_rmax(),
  1260. trans=self.transData.frozen(),
  1261. trans_inverse=self.transData.inverted().frozen(),
  1262. r_label_angle=self.get_rlabel_position(),
  1263. x=x,
  1264. y=y,
  1265. mode=mode)
  1266. def end_pan(self):
  1267. del self._pan_start
  1268. def drag_pan(self, button, key, x, y):
  1269. p = self._pan_start
  1270. if p.mode == 'drag_r_labels':
  1271. (startt, startr), (t, r) = p.trans_inverse.transform(
  1272. [(p.x, p.y), (x, y)])
  1273. # Deal with theta
  1274. dt = np.rad2deg(startt - t)
  1275. self.set_rlabel_position(p.r_label_angle - dt)
  1276. trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0)
  1277. trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0)
  1278. for t in self.yaxis.majorTicks + self.yaxis.minorTicks:
  1279. t.label1.set_va(vert1)
  1280. t.label1.set_ha(horiz1)
  1281. t.label2.set_va(vert2)
  1282. t.label2.set_ha(horiz2)
  1283. elif p.mode == 'zoom':
  1284. (startt, startr), (t, r) = p.trans_inverse.transform(
  1285. [(p.x, p.y), (x, y)])
  1286. # Deal with r
  1287. scale = r / startr
  1288. self.set_rmax(p.rmax / scale)
  1289. # To keep things all self-contained, we can put aliases to the Polar classes
  1290. # defined above. This isn't strictly necessary, but it makes some of the
  1291. # code more readable, and provides a backwards compatible Polar API. In
  1292. # particular, this is used by the :doc:`/gallery/specialty_plots/radar_chart`
  1293. # example to override PolarTransform on a PolarAxes subclass, so make sure that
  1294. # that example is unaffected before changing this.
  1295. PolarAxes.PolarTransform = PolarTransform
  1296. PolarAxes.PolarAffine = PolarAffine
  1297. PolarAxes.InvertedPolarTransform = InvertedPolarTransform
  1298. PolarAxes.ThetaFormatter = ThetaFormatter
  1299. PolarAxes.RadialLocator = RadialLocator
  1300. PolarAxes.ThetaLocator = ThetaLocator