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 19 Python
使用Python设置tmpfs来加速项目的教程
Apr 17 Python
Python使用内置json模块解析json格式数据的方法
Jul 20 Python
python使用logging模块发送邮件代码示例
Jan 18 Python
浅谈Python批处理文件夹中的txt文件
Mar 11 Python
python实现共轭梯度法
Jul 03 Python
pycharm无法导入本地模块的解决方式
Feb 12 Python
Django-silk性能测试工具安装及使用解析
Nov 28 Python
python re模块常见用法例举
Mar 01 Python
Python绘制分类图的方法
Apr 20 Python
七个Python必备的GUI库
Apr 27 Python
OpenCV-Python使用cv2实现傅里叶变换
Jun 09 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
雄兵连:第三季确定会出,不过时间未定,鹤熙是第三季的主角!
2020/03/13 国漫
用js进行url编码后用php反解以及用php实现js的escape功能函数总结
2010/02/08 PHP
PHP用mysql数据库存储session的代码
2010/03/05 PHP
php自定义函数call_user_func和call_user_func_array详解
2011/07/14 PHP
PHP中实现接收多个name相同但Value不相同表单数据实例
2015/02/03 PHP
php读取出一个文件夹及其子文件夹下所有文件的方法示例
2017/06/15 PHP
jquery ajax post提交数据乱码
2013/11/05 Javascript
node.js中的fs.writeFile方法使用说明
2014/12/14 Javascript
jquery 插件实现多行文本框[textarea]自动高度
2015/03/04 Javascript
js实现超酷的照片墙展示效果图附源码下载
2015/10/08 Javascript
使用jquery插件qrcode生成二维码
2015/10/22 Javascript
JS排序方法(sort,bubble,select,insert)代码汇总
2016/01/30 Javascript
浅析javascript异步执行函数导致的变量变化问题解决思路
2016/05/13 Javascript
js判断radiobuttonlist的选中值显示/隐藏其它模块的实现方法
2016/08/25 Javascript
浅谈jquery的html方法里包含特殊字符的处理
2016/11/30 Javascript
BOM之navigator对象和用户代理检测
2017/02/10 Javascript
jquery实现的table排序功能示例
2017/03/10 Javascript
微信小程序 新建登录页并实现tabBar隐藏
2017/06/13 Javascript
Thinkphp5微信小程序获取用户信息接口的实例详解
2017/09/26 Javascript
Vue精简版风格概述
2018/01/30 Javascript
js操作二进制数据方法
2018/03/03 Javascript
JS实现的3des+base64加密解密算法完整示例
2018/05/18 Javascript
javascript中toFixed()四舍五入使用方法详解
2018/09/28 Javascript
微信小程序bindinput与bindsubmit的区别实例分析
2019/04/17 Javascript
[01:34:42]NAVI vs EG 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
[56:13]DOTA2-DPC中国联赛定级赛 LBZS vs Phoenix BO3第一场 1月10日
2021/03/11 DOTA
在Python中操作文件之read()方法的使用教程
2015/05/24 Python
python批量下载抖音视频
2019/06/17 Python
python爬虫开发之Request模块从安装到详细使用方法与实例全解
2020/03/09 Python
小学运动会广播稿200字(十二篇)
2014/01/14 职场文书
班风口号
2014/06/18 职场文书
老人与海读书笔记
2015/06/26 职场文书
初中英语教师个人工作总结2015
2015/07/21 职场文书
职场干货:简历中的自我评价应该这样写!
2019/05/06 职场文书
2019通用版导游词范本!
2019/08/07 职场文书
导游词之西递宏村
2019/12/10 职场文书