"Python tutorial" to draw a nice bar chart

Source: Internet
Author: User
Matplotlib is an open source project based on the Python language, which is designed to provide Python with a data-drawing package, this article briefly describes how to use the package to draw a nice bar chart.

Import command

1) Set the working environment%CD "F:\\dropbox\\python" 2) Import package imports Matplotlib.pyplot as Pltimport numpy as Npfrom matplotlib.image import Bboximagefrom matplotlib._png Import read_pngimport matplotlib.colorsfrom matplotlib.cbook import Get_sample_ DataImport pandas as PD3) read Data data=pd.read_csv ("Car.csv") 4) define and draw the image class Ribbonbox (object): Original_image = Read_png ( Get_sample_data ("Minduka_present_blue_pack.png", asfileobj=false)) cut_location = 70b_and_h = original_image[:,:,2] color = original_image[:,:,2]-Original_image[:,:,0]alpha = ORIGINAL_IMAGE[:,:,3]NX = Original_image.shape[1]def __ init__ (self, color): RGB = MATPLOTLIB.COLORS.COLORCONVERTER.TO_RGB (color) im = Np.empty (Self.original_image.shape, Self.original_image.dtype) Im[:,:,:3] = self.b_and_h[:,:,np.newaxis]im[:,:,:3]-= self.color[:,:,np.newaxis]* (1.- Np.array (RGB)) im[:,:,3] = self.alphaself.im = Imdef get_stretched_image (self, stretch_factor): Stretch_factor = max ( Stretch_factor, 1) NY, NX, nch = self.im.shapeny2 = Int (ny*stretch_factor) Stretched_image = Np.empty ((Ny2, NX, nch), self.im.dtype) cut = self.im[self.cut_location,:,:]stretched_image[:,:,:] = Cutstretched_ Image[:self.cut_location,:,:] = \self.im[:self.cut_location,:,:]stretched_image[-(ny-self.cut_location):,:,:] = \ self.im[-(ny-self.cut_location):,:,:]self._cached_im = Stretched_imagereturn Stretched_imageclass RibbonBoxImage ( Bboximage): ZOrder = 1def __init__ (self, bbox, Color,cmap = None,norm = None,interpolation=none,origin=none,filternorm=1 , filterrad=4.0,resample = False,**kwargs): bboximage.__init__ (self, bbox,cmap = Cmap,norm = norm,interpolation= Interpolation,origin=origin,filternorm=filternorm,filterrad=filterrad,resample = Resample,**kwargs) self._ Ribbonbox = Ribbonbox (color) Self._cached_ny = Nonedef draw (self, renderer, *args, **kwargs): Bbox = Self.get_window_ Extent (renderer) Stretch_factor = Bbox.height/bbox.widthny = Int (stretch_factor*self._ribbonbox.nx) if self._cached_ NY! = Ny:arr = Self._ribbonbox.get_stretched_image (stretch_factor) Self.set_array (arr) self._cacheD_ny = Nybboximage.draw (self, renderer, *args, **kwargs) if 1:from matplotlib.transforms import Bbox, Transformedbboxfrom Matplotlib.ticker import scalarformatterfig, ax = plt.subplots () years = Np.arange (2001,2008) box_colors = [(0.8, 0.2, 0.2) , (0.2, 0.8, 0.2), (0.2, 0.2, 0.8), (0.7, 0.5, 0.8), (0.3, 0.8, 0.7), (0.4, 0.6, 0.3), (0.5, 0.5, 0.1),]heights = data[' Price ']f MT = Scalarformatter (useoffset=false) ax.xaxis.set_major_formatter (FMT) for year, h, BC in Zip (years, heights, box_colors ): bbox0 = bbox.from_extents (year-0.4, 0., year+0.4, h) Bbox = Transformedbbox (bbox0, ax.transdata) Rb_patch = Ribbonboximage (bbox, BC, interpolation= "Bicubic") ax.add_artist (Rb_patch) ax.annotate (H, (year, h), va= "Bottom", ha= " Center ") Ax.set_title (' The Price of Car ') patch_gradient = Bboximage (ax.bbox,interpolation=" Bicubic ", zorder=0.1,) Gradient = Np.zeros ((2, 2, 4), dtype=np.float) Gradient[:,:,:3] = [1, 1, 0.] gradient[:,:,3] = [[0.1, 0.3],[0.3, 0.5]]patch_gradient.set_array (gradient) ax.add_artist (patch_gradient) ax.seT_xlim (years[0]-0.5, years[-1]+0.5) ax.set_ylim (0, 15000) 5) Save Image Fig.savefig (' The Price of Car.png ') plt.show () 

The output image is as follows

The above is the "Python tutorial" to draw a beautiful histogram of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.