演示丝带盒

演示丝带盒示例

  1. import numpy as np
  2. from matplotlib import cbook, colors as mcolors
  3. from matplotlib.image import BboxImage
  4. import matplotlib.pyplot as plt
  5. class RibbonBox:
  6. original_image = plt.imread(
  7. cbook.get_sample_data("Minduka_Present_Blue_Pack.png"))
  8. cut_location = 70
  9. b_and_h = original_image[:, :, 2:3]
  10. color = original_image[:, :, 2:3] - original_image[:, :, 0:1]
  11. alpha = original_image[:, :, 3:4]
  12. nx = original_image.shape[1]
  13. def __init__(self, color):
  14. rgb = mcolors.to_rgba(color)[:3]
  15. self.im = np.dstack(
  16. [self.b_and_h - self.color * (1 - np.array(rgb)), self.alpha])
  17. def get_stretched_image(self, stretch_factor):
  18. stretch_factor = max(stretch_factor, 1)
  19. ny, nx, nch = self.im.shape
  20. ny2 = int(ny*stretch_factor)
  21. return np.vstack(
  22. [self.im[:self.cut_location],
  23. np.broadcast_to(
  24. self.im[self.cut_location], (ny2 - ny, nx, nch)),
  25. self.im[self.cut_location:]])
  26. class RibbonBoxImage(BboxImage):
  27. zorder = 1
  28. def __init__(self, bbox, color, **kwargs):
  29. super().__init__(bbox, **kwargs)
  30. self._ribbonbox = RibbonBox(color)
  31. def draw(self, renderer, *args, **kwargs):
  32. bbox = self.get_window_extent(renderer)
  33. stretch_factor = bbox.height / bbox.width
  34. ny = int(stretch_factor*self._ribbonbox.nx)
  35. if self.get_array() is None or self.get_array().shape[0] != ny:
  36. arr = self._ribbonbox.get_stretched_image(stretch_factor)
  37. self.set_array(arr)
  38. super().draw(renderer, *args, **kwargs)
  39. if True:
  40. from matplotlib.transforms import Bbox, TransformedBbox
  41. from matplotlib.ticker import ScalarFormatter
  42. # Fixing random state for reproducibility
  43. np.random.seed(19680801)
  44. fig, ax = plt.subplots()
  45. years = np.arange(2004, 2009)
  46. box_colors = [(0.8, 0.2, 0.2),
  47. (0.2, 0.8, 0.2),
  48. (0.2, 0.2, 0.8),
  49. (0.7, 0.5, 0.8),
  50. (0.3, 0.8, 0.7),
  51. ]
  52. heights = np.random.random(years.shape) * 7000 + 3000
  53. fmt = ScalarFormatter(useOffset=False)
  54. ax.xaxis.set_major_formatter(fmt)
  55. for year, h, bc in zip(years, heights, box_colors):
  56. bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
  57. bbox = TransformedBbox(bbox0, ax.transData)
  58. rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")
  59. ax.add_artist(rb_patch)
  60. ax.annotate(r"%d" % (int(h/100.)*100),
  61. (year, h), va="bottom", ha="center")
  62. patch_gradient = BboxImage(ax.bbox, interpolation="bicubic", zorder=0.1)
  63. gradient = np.zeros((2, 2, 4))
  64. gradient[:, :, :3] = [1, 1, 0.]
  65. gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]] # alpha channel
  66. patch_gradient.set_array(gradient)
  67. ax.add_artist(patch_gradient)
  68. ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
  69. ax.set_ylim(0, 10000)
  70. plt.show()

下载这个示例