将图像应用于pyplot python条形图 [英] apply images to pyplot python bar graphs

查看:65
本文介绍了将图像应用于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)

谢谢

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没有内置的方法来执行此操作,尽管matplotlib确实允许在条形图中使用阴影线.例如,请参见 hatch_demo .

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

但是以条形图的形式组合多个对plt.imshow的调用并不是很难.这是一个相当粗糙的函数,可以使用图像的标志思想将其用作图像来绘制基本的条形图.

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)

不对xy轴做任何花哨的操作,将返回此图.

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

这篇关于将图像应用于pyplot python条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆