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 判断一个进程是否存在
Apr 09 Python
python 正则式 概述及常用字符
May 07 Python
Python文件与文件夹常见基本操作总结
Sep 19 Python
Python用户推荐系统曼哈顿算法实现完整代码
Dec 01 Python
Python编程scoketServer实现多线程同步实例代码
Jan 29 Python
Python中存取文件的4种不同操作
Jul 02 Python
python networkx 包绘制复杂网络关系图的实现
Jul 10 Python
python实现LBP方法提取图像纹理特征实现分类的步骤
Jul 11 Python
Python使用itchat模块实现简单的微信控制电脑功能示例
Aug 26 Python
Python 自动登录淘宝并保存登录信息的方法
Sep 04 Python
python实现百度OCR图片识别过程解析
Jan 17 Python
Python如何爬取qq音乐歌词到本地
Jun 01 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
实用函数2
2007/11/08 PHP
PHP 多进程 解决难题
2009/06/22 PHP
Zend的MVC机制使用分析(二)
2013/05/02 PHP
PHP实现类似于C语言的文件读取及解析功能
2017/09/01 PHP
PhpStorm 如何优雅的调试Hyperf的方法步骤
2019/11/24 PHP
可输入的下拉框
2006/06/19 Javascript
JQuery 使用attr方法实现下拉列表选中
2014/10/13 Javascript
jQuery中delegate()方法用法实例
2015/01/19 Javascript
jQuery实现高亮显示网页关键词的方法
2015/08/07 Javascript
JavaScript实现输入框(密码框)出现提示语
2016/01/12 Javascript
Jquery 自定义事件实现发布/订阅的简单实例
2016/06/12 Javascript
jQuery树形控件zTree使用小结
2016/08/02 Javascript
JavaScript学习教程之cookie与webstorage
2019/06/23 Javascript
浅谈v-for 和 v-if 并用时筛选条件方法
2019/11/07 Javascript
vue 使用post/get 下载导出文件操作
2020/08/07 Javascript
[03:55]2014DOTA2国际邀请赛 Fnatic经理采访赢DK在情理之中
2014/07/10 DOTA
[51:05]DOTA2上海特级锦标赛主赛事日 - 5 败者组决赛Liquid VS EG第一局
2016/03/06 DOTA
bat和python批量重命名文件的实现代码
2016/05/19 Python
Python实现带参数的用户验证功能装饰器示例
2018/12/14 Python
python之线程通过信号pyqtSignal刷新ui的方法
2019/01/11 Python
python 杀死自身进程的实现方法
2019/07/01 Python
Python 如何操作 SQLite 数据库
2020/08/17 Python
使用phonegap播放音频的实现方法
2017/03/31 HTML / CSS
浅析HTML5 Landmark
2020/09/11 HTML / CSS
mysql的最长数据库名,表名,字段名可以是多长
2014/04/21 面试题
什么是虚拟内存?虚拟内存有什么优势?
2012/02/19 面试题
医学院四年学习生活的自我评价
2013/11/06 职场文书
《在山的那边》教学反思
2014/02/23 职场文书
北京申奥口号
2014/06/19 职场文书
主题党日活动总结
2014/07/08 职场文书
竞选班干部演讲稿100字
2014/08/20 职场文书
机关干部四风问题自查报告及整改措施
2014/10/26 职场文书
教师党的群众路线教育实践活动学习笔记
2014/11/05 职场文书
毕业设计致谢语
2015/05/14 职场文书
python flask框架快速入门
2021/05/14 Python
MySQL数据库如何查看表占用空间大小
2022/06/10 MySQL