当前位置:Gxlcms > Python > 【Python教程】绘制漂亮的柱状图

【Python教程】绘制漂亮的柱状图

时间:2021-07-01 10:21:17 帮助过:537人阅读

Matplotlib是基于Python语言的开源项目,其旨在为Python提供一个数据绘图包,本文简单介绍如何使用该程序包绘制漂亮的柱状图。

导入命令

  1. 1)设置工作环境%cd "F:\\Dropbox\\python"2)导入程序包import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.image import BboxImage
  4. from matplotlib._png import read_png
  5. import matplotlib.colors
  6. from matplotlib.cbook import get_sample_data
  7. import pandas as pd3)读取数据data=pd.read_csv("CAR.csv")4)定义并绘制图像
  8. class RibbonBox(object):original_image = read_png(get_sample_data("Minduka_Present_Blue_Pack.png",asfileobj=False))cut_location = 70
  9. b_and_h = original_image[:,:,2]
  10. color = original_image[:,:,2] - original_image[:,:,0]
  11. alpha = original_image[:,:,3]
  12. nx = original_image.shape[1]def __init__(self, color):
  13. rgb = matplotlib.colors.colorConverter.to_rgb(color)im = np.empty(self.original_image.shape,
  14. self.original_image.dtype)im[:,:,:3] = self.b_and_h[:,:,np.newaxis]
  15. im[:,:,:3] -= self.color[:,:,np.newaxis]*(1.-np.array(rgb))
  16. im[:,:,3] = self.alphaself.im = imdef get_stretched_image(self, stretch_factor):
  17. stretch_factor = max(stretch_factor, 1)
  18. ny, nx, nch = self.im.shape
  19. ny2 = int(ny*stretch_factor)stretched_image = np.empty((ny2, nx, nch),
  20. self.im.dtype)
  21. cut = self.im[self.cut_location,:,:]
  22. stretched_image[:,:,:] = cut
  23. stretched_image[:self.cut_location,:,:] = \
  24. self.im[:self.cut_location,:,:]
  25. stretched_image[-(ny-self.cut_location):,:,:] = \
  26. self.im[-(ny-self.cut_location):,:,:]self._cached_im = stretched_image
  27. return stretched_image
  28. class RibbonBoxImage(BboxImage):
  29. zorder = 1def __init__(self, bbox, color,
  30. cmap = None,
  31. norm = None,
  32. interpolation=None,
  33. origin=None,
  34. filternorm=1,
  35. filterrad=4.0,
  36. resample = False,
  37. **kwargs
  38. ):BboxImage.__init__(self, bbox,
  39. cmap = cmap,
  40. norm = norm,
  41. interpolation=interpolation,
  42. origin=origin,
  43. filternorm=filternorm,
  44. filterrad=filterrad,
  45. resample = resample,
  46. **kwargs
  47. )self._ribbonbox = RibbonBox(color)
  48. self._cached_ny = Nonedef draw(self, renderer, *args, **kwargs):bbox = self.get_window_extent(renderer)
  49. stretch_factor = bbox.height / bbox.widthny = int(stretch_factor*self._ribbonbox.nx)
  50. if self._cached_ny != ny:
  51. arr = self._ribbonbox.get_stretched_image(stretch_factor)
  52. self.set_array(arr)
  53. self._cached_ny = nyBboxImage.draw(self, renderer, *args, **kwargs)if 1:
  54. from matplotlib.transforms import Bbox, TransformedBbox
  55. from matplotlib.ticker import ScalarFormatterfig, ax = plt.subplots()years = np.arange(2001,2008)
  56. box_colors = [(0.8, 0.2, 0.2),
  57. (0.2, 0.8, 0.2),
  58. (0.2, 0.2, 0.8),
  59. (0.7, 0.5, 0.8),
  60. (0.3, 0.8, 0.7),
  61. (0.4, 0.6, 0.3),
  62. (0.5, 0.5, 0.1),
  63. ]
  64. heights = data['price']fmt = ScalarFormatter(useOffset=False)
  65. ax.xaxis.set_major_formatter(fmt)for year, h, bc in zip(years, heights, box_colors):
  66. bbox0 = Bbox.from_extents(year-0.4, 0., year+0.4, h)
  67. bbox = TransformedBbox(bbox0, ax.transData)
  68. rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")ax.add_artist(rb_patch)
  69. ax.annotate(h,
  70. (year, h), va="bottom", ha="center")
  71. ax.set_title('The Price of Car')patch_gradient = BboxImage(ax.bbox,
  72. interpolation="bicubic",
  73. zorder=0.1,
  74. )
  75. gradient = np.zeros((2, 2, 4), dtype=np.float)
  76. gradient[:,:,:3] = [1, 1, 0.]
  77. gradient[:,:,3] = [[0.1, 0.3],[0.3, 0.5]]
  78. patch_gradient.set_array(gradient)
  79. ax.add_artist(patch_gradient)ax.set_xlim(years[0]-0.5, years[-1]+0.5)
  80. ax.set_ylim(0, 15000)5)保存图像fig.savefig('The Price of Car.png')
  81. plt.show()

输出图像如下

979.jpg

以上就是【Python教程】绘制漂亮的柱状图的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行