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中的一些类型转换函数小结
Feb 10 Python
用Python的Django框架来制作一个RSS阅读器
Jul 22 Python
python下读取公私钥做加解密实例详解
Mar 29 Python
创建pycharm的自定义python模板方法
May 23 Python
Flask之flask-script模块使用
Jul 26 Python
Django uwsgi Nginx 的生产环境部署详解
Feb 02 Python
python批量创建指定名称的文件夹
Mar 21 Python
Python实现不规则图形填充的思路
Feb 02 Python
Python chardet库识别编码原理解析
Feb 18 Python
python图片指定区域替换img.paste函数的使用
Apr 09 Python
opencv python 对指针仪表读数识别的两种方式
Jan 14 Python
教你使用一行Python代码玩遍童年的小游戏
Aug 23 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
PHP rawurlencode与urlencode函数的深入分析
2013/06/08 PHP
PHP 常用的header头部定义汇总
2015/06/19 PHP
WordPress中用于更新伪静态规则的PHP代码实例讲解
2015/12/18 PHP
通过PHP自带的服务器来查看正则匹配结果的方法
2015/12/24 PHP
Yii2 RESTful中api的使用及开发实例详解
2016/07/06 PHP
javascript 日历提醒系统( 兼容所有浏览器 )
2009/04/07 Javascript
Extjs学习笔记之一 初识Extjs之MessageBox
2010/01/07 Javascript
jQuery 获取对象 定位子对象
2010/05/31 Javascript
jQuery前台数据获取实现代码
2011/03/16 Javascript
javascript 运算数的求值顺序
2011/08/23 Javascript
javascript获取xml节点的最大值(实现代码)
2013/12/11 Javascript
在IE8上JS实现combobox支持拼音检索功能
2016/05/23 Javascript
jQuery插件zTree实现获取一级节点数据的方法
2017/03/08 Javascript
vue的全局变量和全局拦截请求器的示例代码
2018/09/13 Javascript
nuxt 每个页面head标签内容设置方式
2020/11/05 Javascript
[36:05]DOTA2亚洲邀请赛 3.31 小组赛 A组 Liquid vs Optic
2018/04/01 DOTA
Python标准库与第三方库详解
2014/07/22 Python
基于python的Tkinter实现一个简易计算器
2015/12/31 Python
Pycharm设置界面全黑的方法
2018/05/23 Python
Python 实现try重新执行
2019/12/21 Python
解决matplotlib.pyplot在Jupyter notebook中不显示图像问题
2020/04/22 Python
Django ORM判断查询结果是否为空,判断django中的orm为空实例
2020/07/09 Python
pandas使用函数批量处理数据(map、apply、applymap)
2020/11/27 Python
Web前端页面跳转并取到值
2017/04/24 HTML / CSS
美国领先的低折扣旅行网站:Hotwire
2019/01/19 全球购物
美国婴儿用品及配件购买网站:Munchkin
2019/04/03 全球购物
G-Form护具官方网站:美国运动保护装备
2019/09/04 全球购物
mysql_pconnect()和mysql_connect()有什么区别
2012/05/25 面试题
应届生自荐信范文
2014/02/21 职场文书
《金钱的魔力》教学反思
2014/02/24 职场文书
教师节活动总结
2014/08/29 职场文书
小学生安全教育广播稿
2014/10/20 职场文书
2014年保洁工作总结
2014/11/24 职场文书
四年级学生期末评语
2014/12/26 职场文书
Logback 使用TurboFilter实现日志级别等内容的动态修改操作
2021/08/30 Java/Android
如何设置多台电脑共享打印机?多台电脑共享打印机的方法
2022/04/08 数码科技