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+matplotlib实现填充螺旋实例
  • python+matplotlib实现鼠标移动三角形高亮及索引显示
  • python+matplotlib演示电偶极子实例代码
  • Python+matplotlib+numpy实现在不同平面的二维条形图
  • Python+matplotlib+numpy绘制精美的条形统计图
  • python+matplotlib绘制简单的海豚(顶点和节点的操作)
  • Python使用Matplotlib实现Logos设计代码
  • Python使用matplotlib填充图形指定区域代码示例
(0)

相关推荐

  • python+matplotlib演示电偶极子实例代码

    使用matplotlib.tri.CubicTriInterpolator.演示变化率计算: 完整实例: from matplotlib.tri import ( Triangulation, UniformTriRefiner, CubicTriInterpolator) import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np #---------------------------------

  • Python使用Matplotlib实现Logos设计代码

    本文主要展示了使用matplotlib设计logo的示例及完整代码,首先看下其演示结果: Python代码如下: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.cm as cm mpl.rcParams['xtick.labelsize'] = 10 mpl.rcParams['ytick.labelsize'] = 12 mpl.rcParams['ax

  • Python+matplotlib+numpy绘制精美的条形统计图

    本文实例主要向大家分享了一个Python+matplotlib+numpy绘制精美的条形统计图的代码,效果展示如下: 完整代码如下: import matplotlib.pyplot as plt from numpy import arange from numpy.random import rand def gbar(ax, x, y, width=0.5, bottom=0): X = [[.6, .6], [.7, .7]] for left, top in zip(x, y): ri

  • python+matplotlib实现鼠标移动三角形高亮及索引显示

    Trifinder事件实例 实例展示Trifinder对象对的使用.当鼠标移动到一个被分割的三角形上,这个三角形高亮显示,并且它的标签在图标题显示. 展示下演示结果: 完整代码: import matplotlib.pyplot as plt from matplotlib.tri import Triangulation from matplotlib.patches import Polygon import numpy as np def update_polygon(tri): if t

  • Python+matplotlib实现填充螺旋实例

    填充螺旋演示结果: 实例代码: import matplotlib.pyplot as plt import numpy as np theta = np.arange(0, 8*np.pi, 0.1) a = 1 b = .2 for dt in np.arange(0, 2*np.pi, np.pi/2.0): x = a*np.cos(theta + dt)*np.exp(b*theta) y = a*np.sin(theta + dt)*np.exp(b*theta) dt = dt +

  • python+matplotlib绘制简单的海豚(顶点和节点的操作)

    海豚 本文例子主要展示了如何使用补丁.路径和转换类绘制和操作给定的顶点和节点的形状. 测试可用. import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D import numpy as n

  • Python使用matplotlib填充图形指定区域代码示例

    本文代码重点在于演示Python扩展库matplotlib.pyplot中fill_between()函数的用法. import numpy as np import matplotlib.pyplot as plt # 生成模拟数据 x = np.arange(0.0, 4.0*np.pi, 0.01) y = np.sin(x) # 绘制正弦曲线 plt.plot(x, y) # 绘制基准水平直线 plt.plot((x.min(),x.max()), (0,0)) # 设置坐标轴标签 pl

  • Python+matplotlib+numpy实现在不同平面的二维条形图

    在不同平面上绘制二维条形图. 本实例制作了一个3d图,其中有二维条形图投射到平面y=0,y=1,等. 演示结果: 完整代码: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) fig = plt.figure() ax = fig.a

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

  • python+matplotlib绘制饼图散点图实例代码

    本文是从matplotlib官网上摘录下来的一个实例,实现的功能是Python+matplotlib绘制自定义饼图作为散点图的标记,具体如下. 首先看下演示效果 实例代码: import numpy as np import matplotlib.pyplot as plt # first define the ratios r1 = 0.2 # 20% r2 = r1 + 0.4 # 40% # define some sizes of the scatter marker sizes = n

  • python+matplotlib绘制3D条形图实例代码

    本文分享的实例主要实现的是Python+matplotlib绘制一个有阴影和没有阴影的3D条形图,具体如下. 首先看看演示效果: 完整代码如下: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # setup the figure and axes fig = plt.figure(figsize=(8, 3)) ax1 = fig.add_subplot(121

  • python+matplotlib绘制旋转椭圆实例代码

    旋转椭圆 实例代码: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse delta = 45.0 # degrees angles = np.arange(0, 360 + delta, delta) ells = [Ellipse((1, 1), 4, 2, a) for a in angles] a = plt.subplot(111, aspect='equal

  • 使用python matplotlib画折线图实例代码

    目录 matplotlib简介 1.画折线图[一条示例] 2.画折线图带数据标签 3.画多条折线图: 4.画多条折线图分别带数据标签: 总结 matplotlib简介 matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中. 它的文档相当完备,并且Gallery页面中有上百幅缩略图,打开之后都有源程序.因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基

  • Python matplotlib绘制散点图的实例代码

    前言 前面说到的主要是matplotlib对于图像的基础操作,然后从这篇开始,主要说一下点图,分析点图在实际问题的数据处理中应用非常广泛,比如说逻辑回归是利用现有的数据点通过拟合得到一定的函数关系,甚至生活中,物体运动的轨迹,也可以看做是连续的点绘制而成,还有图像,也是很多个像素点堆砌而成的,在图像处理中经常会针对单个像素点进行处理. 现在的深度学习或者机器学习,模型都是固定的,大多 不需要怎么改动,而能提升训练效果的,最重要的就是能更好的处理数据,而很多数据本身就是点集,利用matplotli

  • matplotlib作图添加表格实例代码

    本文所示代码主要是通过Python+matplotlib实现作图,并且在图中添加表格的功能,具体如下. 代码 import matplotlib.pyplot as plt import numpy as np plt.figure() ax = plt.gca() y = np.random.randn(9) col_labels = ['col1','col2','col3'] row_labels = ['row1','row2','row3'] table_vals = [[11,12,

  • python中Matplotlib绘制直线的实例代码

    说明 1.导入模块pyplot,并指定别名plt,以避免重复输入pyplot.模块化pyplot包含许多用于制作图表的功能. 2.将绘制的直线坐标传递给函数plot(). 3.通过函数plt.show()打开Matplotlib,显示所绘图形. 实例 import matplotlib.pyplot as plt #将(0,1)点和(2,4)连起来 plt.plot([0,2],[1,4]) plt.show() 相关实例扩展: 线型图 import matplotlib.pyplot as p

  • Python绘制3d螺旋曲线图实例代码

    Line plots Axes3D.plot(xs, ys, *args, **kwargs) 绘制2D或3D数据 参数 描述 xs, ys X轴,Y轴坐标定点 zs Z值,每一个点的值都是1 zdir 绘制2D集合时使用z的方向 其他的参数:plot() Python代码: import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as

随机推荐