python+matplotlib实现礼盒柱状图实例代码


Posted in Python onJanuary 16, 2018

演示结果:

python+matplotlib实现礼盒柱状图实例代码

完整代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import BboxImage

from matplotlib._png import read_png
import matplotlib.colors
from matplotlib.cbook import get_sample_data


class RibbonBox(object):

  original_image = read_png(get_sample_data("Minduka_Present_Blue_Pack.png",
                       asfileobj=False))
  cut_location = 70
  b_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.to_rgba(color)[:3]

    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.alpha

    self.im = im

  def get_stretched_image(self, stretch_factor):
    stretch_factor = max(stretch_factor, 1)
    ny, nx, nch = self.im.shape
    ny2 = int(ny*stretch_factor)

    stretched_image = np.empty((ny2, nx, nch),
                  self.im.dtype)
    cut = self.im[self.cut_location, :, :]
    stretched_image[:, :, :] = cut
    stretched_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_image
    return stretched_image


class RibbonBoxImage(BboxImage):
  zorder = 1

  def __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 = None

  def draw(self, renderer, *args, **kwargs):

    bbox = self.get_window_extent(renderer)
    stretch_factor = bbox.height / bbox.width

    ny = 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 = ny

    BboxImage.draw(self, renderer, *args, **kwargs)


if 1:
  from matplotlib.transforms import Bbox, TransformedBbox
  from matplotlib.ticker import ScalarFormatter

  # Fixing random state for reproducibility
  np.random.seed(19680801)

  fig, ax = plt.subplots()

  years = np.arange(2004, 2009)
  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),
         ]
  heights = np.random.random(years.shape) * 7000 + 3000

  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(r"%d" % (int(h/100.)*100),
          (year, h), va="bottom", ha="center")

  patch_gradient = BboxImage(ax.bbox,
                interpolation="bicubic",
                zorder=0.1,
                )
  gradient = np.zeros((2, 2, 4), dtype=float)
  gradient[:, :, :3] = [1, 1, 0.]
  gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]] # alpha channel
  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, 10000)

  fig.savefig('ribbon_box.png')
  plt.show()

总结

以上就是本文关于python+matplotlib实现礼盒柱状图实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
Python实现模拟时钟代码推荐
Nov 08 Python
Python操作SQLite数据库的方法详解【导入,创建,游标,增删改查等】
Jul 11 Python
pytorch训练imagenet分类的方法
Jul 27 Python
Python基础之循环语句用法示例【for、while循环】
Mar 23 Python
Python3使用Matplotlib 绘制精美的数学函数图形
Apr 11 Python
python Pandas如何对数据集随机抽样
Jul 29 Python
pycharm重命名文件的方法步骤
Jul 29 Python
django rest framework vue 实现用户登录详解
Jul 29 Python
Python利用WMI实现ping命令的例子
Aug 14 Python
PyTorch中Tensor的拼接与拆分的实现
Aug 18 Python
python实现统计代码行数的小工具
Sep 19 Python
解决Tensorflow 使用时cpu编译不支持警告的问题
Feb 03 Python
Python+matplotlib实现填充螺旋实例
Jan 15 #Python
python+matplotlib实现鼠标移动三角形高亮及索引显示
Jan 15 #Python
wxPython之解决闪烁的问题
Jan 15 #Python
详细解读tornado协程(coroutine)原理
Jan 15 #Python
Python之ReportLab绘制条形码和二维码的实例
Jan 15 #Python
Tornado高并发处理方法实例代码
Jan 15 #Python
使用Python实现windows下的抓包与解析
Jan 15 #Python
You might like
Re:从零开始的异世界生活 第2季 开播啦
2020/07/24 日漫
PHP的开发框架的现状和展望
2007/03/16 PHP
如何使用“PHP” 彩蛋进行敏感信息获取
2013/08/07 PHP
简单谈谈PHP vs Node.js
2015/07/17 PHP
Zend Framework实现多文件上传功能实例
2016/03/21 PHP
浅谈php中curl、fsockopen的应用
2016/12/10 PHP
js之WEB开发调试利器:Firebug 下载
2007/01/13 Javascript
HTML代码中标签的全部属性 中文注释说明
2009/03/26 Javascript
JS 遮照层实现代码
2010/03/31 Javascript
不依赖Flash和任何JS库实现文本复制与剪切附源码下载
2015/10/09 Javascript
原生js实现返回顶部缓冲效果
2017/01/18 Javascript
简单的jQuery拖拽排序效果的实现(增强动态)
2017/02/09 Javascript
Input文本框随着输入内容多少自动延伸的实现
2017/02/15 Javascript
JavaScript简单计算人的年龄示例
2017/04/15 Javascript
vue-cli实现多页面多路由的示例代码
2018/01/30 Javascript
layui中使用jquery控制radio选中事件的示例代码
2018/08/15 jQuery
js实现简单分页导航栏效果
2019/06/28 Javascript
layer实现弹出层自动调节位置
2019/09/05 Javascript
解决layer弹出层中表单不起作用的问题
2019/09/09 Javascript
JS常用正则表达式超全集(密码强度校验,金额校验,IE版本,IPv4,IPv6校验)
2020/02/03 Javascript
vue实现数字滚动效果
2020/06/29 Javascript
Python中列表(list)操作方法汇总
2014/08/18 Python
python3获取两个日期之间所有日期,以及比较大小的实例
2018/04/08 Python
Pandas之Dropna滤除缺失数据的实现方法
2019/06/25 Python
python中68个内置函数的总结与介绍
2020/02/24 Python
Django 自定义404 500等错误页面的实现
2020/03/08 Python
Python3爬虫里关于Splash负载均衡配置详解
2020/07/10 Python
基于HTML5代码实现折叠菜单附源码下载
2015/11/27 HTML / CSS
英国医生在线预约:Top Doctors
2019/10/30 全球购物
优秀民警事迹材料
2014/01/29 职场文书
企业仓管员岗位职责
2014/06/15 职场文书
教师见习报告范文
2014/11/03 职场文书
安全承诺书
2015/01/19 职场文书
学校捐书活动总结
2015/05/08 职场文书
2015年小学重阳节活动总结
2015/07/29 职场文书
PHP策略模式写法
2021/04/01 PHP