python 条形图 stack,将图像应用于pyplot python条形图

So below is a snippet of my code, and it all works fine. Just curious instead of display bars with specific colors, can an image be applied to the bar, such as a countries flag etc. (please ignore my inconsistent order of param passing)

thanks

l_images=["australia.png","turkey.png"] # this is desired

l_colors=["pink","blue"]

if (l_bar_dir=="vertical"):

plt.bar(xs2,ys,tick_label=xs,color=l_colors,bottom=bottoms,width=bar_width,align='center') # set plot to be a bar graph

else:

plt.barh(bottom=xs2,width=ys,tick_label=xs,align='center',color=l_colors) # set plot to be a bar graph

解决方案

AFAIK there's no built-in way to do this, although matplotlib does allow hatches in bar plots. See for example, hatch_demo.

But it's not terribly difficult to put together several calls to plt.imshow in the form of a bar plot. Here is a rather crude function that could be used to make basic bar plots using images, using your idea of flags as the images.

import numpy as np

import matplotlib.pyplot as plt

from scipy.misc import imread

def image_plot(heights, images, spacing=0):

# Iterate through images and data, autoscaling the width to

# the aspect ratio of the image

for i, (height, img) in enumerate(zip(heights, images)):

AR = img.shape[1] / img.shape[0]

width = height * AR

left = width*i + spacing*i

right = left + width

plt.imshow(img, extent=[left, right, 0, height])

# Set x,y limits on plot window

plt.xlim(0, right)

plt.ylim(0, max(heights)*1.1)

# Read in flag images

usa_flag = imread('american_flag.png')

aussie_flag = imread('australian_flag.png').swapaxes(0, 1)

turkish_flag = imread('turkish_flag.png').swapaxes(0, 1)

# Make up some data about each country

usa_data = 33

aussie_data = 36

turkish_data = 27

data = [usa_data, aussie_data, turkish_data]

flags = [usa_flag, aussie_flag, turkish_flag]

image_plot(data, flags, spacing=2)

Without doing anything fancy to the x and y axes, returns this plot.

23a05bc77cdbd4b29e2ae99a0ecf6150.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值