Guest User

Untitled

a guest
Nov 23rd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.31 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import seaborn as sns # improves plot aesthetics
  4.  
  5.  
  6. def _invert(x, limits):
  7. """inverts a value x on a scale from
  8. limits[0] to limits[1]"""
  9. return limits[1] - (x - limits[0])
  10.  
  11. def _scale_data(data, ranges):
  12. """scales data[1:] to ranges[0],
  13. inverts if the scale is reversed"""
  14. # for d, (y1, y2) in zip(data[1:], ranges[1:]):
  15. for d, (y1, y2) in zip(data, ranges):
  16. assert (y1 <= d <= y2) or (y2 <= d <= y1)
  17.  
  18. x1, x2 = ranges[0]
  19. d = data[0]
  20.  
  21. if x1 > x2:
  22. d = _invert(d, (x1, x2))
  23. x1, x2 = x2, x1
  24.  
  25. sdata = [d]
  26.  
  27. for d, (y1, y2) in zip(data[1:], ranges[1:]):
  28. if y1 > y2:
  29. d = _invert(d, (y1, y2))
  30. y1, y2 = y2, y1
  31.  
  32. sdata.append((d-y1) / (y2-y1) * (x2 - x1) + x1)
  33.  
  34. return sdata
  35.  
  36. def set_rgrids(self, radii, labels=None, angle=None, fmt=None,
  37. **kwargs):
  38. """
  39. Set the radial locations and labels of the *r* grids.
  40. The labels will appear at radial distances *radii* at the
  41. given *angle* in degrees.
  42. *labels*, if not None, is a ``len(radii)`` list of strings of the
  43. labels to use at each radius.
  44. If *labels* is None, the built-in formatter will be used.
  45. Return value is a list of tuples (*line*, *label*), where
  46. *line* is :class:`~matplotlib.lines.Line2D` instances and the
  47. *label* is :class:`~matplotlib.text.Text` instances.
  48. kwargs are optional text properties for the labels:
  49. %(Text)s
  50. ACCEPTS: sequence of floats
  51. """
  52. # Make sure we take into account unitized data
  53. radii = self.convert_xunits(radii)
  54. radii = np.asarray(radii)
  55. rmin = radii.min()
  56. # if rmin <= 0:
  57. # raise ValueError('radial grids must be strictly positive')
  58.  
  59. self.set_yticks(radii)
  60. if labels is not None:
  61. self.set_yticklabels(labels)
  62. elif fmt is not None:
  63. self.yaxis.set_major_formatter(FormatStrFormatter(fmt))
  64. if angle is None:
  65. angle = self.get_rlabel_position()
  66. self.set_rlabel_position(angle)
  67. for t in self.yaxis.get_ticklabels():
  68. t.update(kwargs)
  69. return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()
  70.  
  71. class ComplexRadar():
  72. def __init__(self, fig, variables, ranges,
  73. n_ordinate_levels=6):
  74. angles = np.arange(0, 360, 360./len(variables))
  75.  
  76. axes = [fig.add_axes([0.1,0.1,0.9,0.9],polar=True,
  77. label = "axes{}".format(i))
  78. for i in range(len(variables))]
  79. l, text = axes[0].set_thetagrids(angles,
  80. labels=variables)
  81. [txt.set_rotation(angle-90) for txt, angle
  82. in zip(text, angles)]
  83. for ax in axes[1:]:
  84. ax.patch.set_visible(False)
  85. ax.grid("off")
  86. ax.xaxis.set_visible(False)
  87. for i, ax in enumerate(axes):
  88. grid = np.linspace(*ranges[i],
  89. num=n_ordinate_levels)
  90. gridlabel = ["{}".format(round(x,2))
  91. for x in grid]
  92. if ranges[i][0] > ranges[i][1]:
  93. grid = grid[::-1] # hack to invert grid
  94. # gridlabels aren't reversed
  95. gridlabel[0] = "" # clean up origin
  96. # ax.set_rgrids(grid, labels=gridlabel, angle=angles[i])
  97. set_rgrids(ax, grid, labels=gridlabel, angle=angles[i])
  98. #ax.spines["polar"].set_visible(False)
  99. ax.set_ylim(*ranges[i])
  100. # variables for plotting
  101. self.angle = np.deg2rad(np.r_[angles, angles[0]])
  102. self.ranges = ranges
  103. self.ax = axes[0]
  104. def plot(self, data, *args, **kw):
  105. sdata = _scale_data(data, self.ranges)
  106. self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
  107. def fill(self, data, *args, **kw):
  108. sdata = _scale_data(data, self.ranges)
  109. self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
  110.  
  111. # example data
  112. variables = ("Normal Scale", "Inverted Scale", "Inverted 2",
  113. "Normal Scale 2", "Normal 3", "Normal 4 %", "Inverted 3 %")
  114. data = (-1.76, 1.1, 1.2,
  115. 4.4, 3.4, 86.8, 20)
  116. ranges = [(-5, 3), (1.5, 0.3), (1.3, 0.5),
  117. (1.7, 4.5), (1.5, 3.7), (70, 87), (100, -50)]
  118. # plotting
  119. fig1 = plt.figure(figsize=(6, 6))
  120. radar = ComplexRadar(fig1, variables, ranges)
  121. radar.plot(data)
  122. radar.fill(data, alpha=0.2)
  123. plt.show()
Add Comment
Please, Sign In to add comment