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 相关文章推荐
Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署教程
Nov 18 Python
为Python的web框架编写MVC配置来使其运行的教程
Apr 30 Python
Python简单实现TCP包发送十六进制数据的方法
Apr 16 Python
python安装cx_Oracle模块常见问题与解决方法
Feb 21 Python
Python实现获取邮箱内容并解析的方法示例
Jun 16 Python
python遍历文件夹找出文件夹后缀为py的文件方法
Oct 21 Python
将自己的数据集制作成TFRecord格式教程
Feb 17 Python
python词云库wordCloud使用方法详解(解决中文乱码)
Feb 17 Python
python Django 反向访问器的外键冲突解决
May 20 Python
Python实现AES加密,解密的两种方法
Oct 03 Python
python查询MySQL将数据写入Excel
Oct 29 Python
python tqdm库的使用
Nov 30 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
杏林同学录(八)
2006/10/09 PHP
理解php Hash函数,增强密码安全
2011/02/25 PHP
php时区转换转换函数
2014/01/07 PHP
php格式化日期和时间格式化示例分享
2014/02/24 PHP
php查找指定目录下指定大小文件的方法
2014/11/28 PHP
php字符串函数学习之strstr()
2015/03/27 PHP
PHP实现的多维数组去重操作示例
2018/07/21 PHP
ThinkPHP框架实现FTP图片上传功能示例
2019/04/08 PHP
图片格式的JavaScript和CSS速查手册
2007/08/20 Javascript
大家未必知道的Js技巧收藏
2008/04/07 Javascript
javascript 子窗体父窗体相互传值方法
2010/05/31 Javascript
一些常用且实用的原生JavaScript函数
2010/09/08 Javascript
javascript工具库代码
2012/03/29 Javascript
JQuery 控制内容长度超出规定长度显示省略号
2014/05/23 Javascript
Javascript的&&和||的另类用法
2014/07/23 Javascript
js随机生成字母数字组合的字符串 随机动画数字
2015/09/02 Javascript
bootstrap多种样式进度条展示
2016/12/20 Javascript
Vue服务端渲染和Vue浏览器端渲染的性能对比(实例PK )
2017/03/31 Javascript
微信小程序 循环及嵌套循环的使用总结
2017/09/26 Javascript
Vue.js项目中管理每个页面的头部标签的两种方法
2018/06/25 Javascript
详解JavaScript的数据类型以及数据类型的转换
2019/04/20 Javascript
python装饰器使用方法实例
2013/11/21 Python
学习python类方法与对象方法
2016/03/15 Python
python非递归全排列实现方法
2017/04/10 Python
python模拟事件触发机制详解
2018/01/19 Python
python3+PyQt5实现拖放功能
2018/04/24 Python
基于python3 pyQt5 QtDesignner实现窗口化猜数字游戏功能
2019/07/15 Python
绿色美容,有机护肤品和化妆品:Safe & Chic
2018/10/29 全球购物
彪马日本官网:PUMA日本
2019/01/31 全球购物
美国在线购买和出售礼品卡网站:EJ Gift Cards
2019/06/09 全球购物
Java servlet面试题
2012/03/04 面试题
管事部库房保管员岗位职责
2014/02/21 职场文书
元旦获奖感言
2014/03/08 职场文书
健康状况证明模板
2014/10/23 职场文书
CSS 圆形进度栏
2021/04/06 HTML / CSS
win11无法添加打印机怎么办? 提示windows无法打开添加打印机的解决办法
2022/04/05 数码科技