polar.py 56 KB

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