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

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

导入命令

1)设置工作环境%cd "F:\Dropbox\python"2)导入程序包import 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)读取数据data=pd.read_csv("CAR.csv")4)定义并绘制图像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']fmt = 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)保存图像fig.savefig('The Price of Car.png')plt.show()

登录后复制

输出图像如下

979.jpg

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

立即学习“Python免费学习笔记(深入)”;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2280142.html

(0)
上一篇 2025年2月27日 17:49:20
下一篇 2025年2月27日 17:49:36

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • 【Python教程】绘制小提琴图

    小提琴图(violinplot)可以理解为箱图(boxplot)加上密度图(kdensity),本文简单介绍在python中如何绘制该图,使用数据为stata软件系统自带auto数据(已导出为csv格式)。 导入命令 1)设置工作环境%cd…

    2025年2月27日
    100
  • 【python教程】网页正文及内容图片提取算法

    抓取单个网站网页内容时通常采用正则匹配的方式,但不同网站之间结构千奇百怪,很难用统一的正则表达式进行匹配。《基于行块分布函数的通用网页正文抽取算法》的作者总结了一般从网页中提取文章正文的方法,提出基于行块分布的正文抽取算法,并给出了 php…

    2025年2月27日 编程技术
    200
  • 【Python教程】地理可视化

    matplotlib是python常用的数据绘制包,其绘图功能强大;而basemap则是matplotlib的一个子包,负责地图绘制。本文简单介绍如何利用该程序包绘制风向图。具体操作如下: 导入命令 1)设置工作环境并导入程序包 %cd “…

    2025年2月27日
    200
  • 【Python教程】绘制仪表盘图

    bokeh(bokeh.js)是一个可在python中提供交互式的可视化库,其支持web浏览器,并提供类似于d3.js软件一样的完美展示功能。本文简单介绍如何使用该程序库绘制仪表盘图,具体操作如下: 导入命令 1)设置工作环境 %cd “F…

    2025年2月27日
    200
  • 【Python教程】地理可视化之二

    basemap是matplotlib的一个子包,负责地图绘制。昨天的推送对如何绘制风向图进行了描述,本文再次利用该包简单介绍如何绘制海洋及海冰温度彩色图示,该图常见于noaa官网。具体操作如下: 导入命令 1)设置工作环境并导入程序包 %c…

    2025年2月27日
    200
  • Python正则表达式【1】

    本文来说说python的正则表达式。 废话不多说了,先开始最简单的: ‘.’:可以匹配除换行符以外的任意单个字符(就是个点)。 ‘*’可以匹配前面的子表达式零次或多次(就是个星号)。 所以上面…

    编程技术 2025年2月27日
    200
  • 高级正则表达式技术(Python版)

    正则表达式是从信息中搜索特定的模式的一把瑞士军刀。它们是一个巨大的工具库,其中的一些功能经常被忽视或未被充分利用。今天我将向你们展示一些正则表达式的高级用法。 举个例子,这是一个我们可能用来检测电话美国电话号码的正则表达式: r’^(1[-…

    编程技术 2025年2月27日
    200
  • Python全栈之路系列之字符串格式化

    This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing &#8…

    编程技术 2025年2月27日
    200
  • Python全栈之路系列之递归

    所谓递归其实就是函数本身调用函数,直到满足指定条件之后一层层退出函数, 例如 从前有座山,山里有座庙,庙里有个老和尚,正在给小和尚讲故事呢!故事是什么呢?“从前有座山,山里有座庙,庙里有个老和尚,正在给小和尚讲故事呢!故事是什么呢?‘从前有…

    编程技术 2025年2月27日
    200
  • Python全栈之路系列之Python3内置函数

    the python interpreter has a number of functions and types built into it that are always available. they are listed here…

    编程技术 2025年2月27日
    200

发表回复

登录后才能评论