在matplotlib图上绘制裁剪的背景图像 [英] Plotting a cropped background image on a matplotlib graph

查看:57
本文介绍了在matplotlib图上绘制裁剪的背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制简单的线图并将背景图像插入到图中.

I'm trying to plot a simple line plot and insert a background image to a plot.

示例图片(带有cat.jpg和dog.jpd):

An example pic (with cat.jpg and dog.jpd):

目前,我有一个代码可以绘制线条(来自pandas数据框)并将图像放置到图形中.但是,图像和线条图根本不会交互".

At the moment I have a code that plots the line (from a pandas dataframe) and places the images into figure. However the images and the line plot do not 'interact' at all.

fig, ax = plt.subplots(figsize=(15,10))
cat = np.array(Image.open('cat.jpg'))
dog = np.array(Image.open('dog.jpg'))
ax.imshow(cat, extent=[0, 10, 0, 18], aspect='auto',   cmap='gray',alpha=0.75)
ax.imshow(dog, extent=[10, 20, 0, 18], aspect='auto', cmap='gray',alpha=0.75)

ax.plot(df['Series'],color='#3cb8fb',alpha=0.95,linewidth=3.0)

plt.show()

推荐答案

您可以使用 plt.fill_between 创建一个覆盖原点和直线之间区域的多边形,然后使用

You can use plt.fill_between to create a polygon that covers the area between the origin and the line, then use the .set_clip_path method of each image object to display only the part of the image that falls within the polygon.

例如:

from matplotlib import pyplot as plt
from scipy.misc import lena

fig, ax = plt.subplots(1, 1)

x = np.linspace(0, 1, 10)
y = np.random.rand(10)
image = ax.imshow(lena(), cmap=plt.cm.gray, extent=[0, 1, 0, 1])
line = ax.plot(x, y, '-r', lw=2)

# invisible clipping polygon
poly = ax.fill_between(x, 0, y, visible=False)
clip = poly.get_paths()[0]

# you will need to do this separately for each of the images in your plot
image.set_clip_path(clip, transform=ax.transData)

plt.show()

这篇关于在matplotlib图上绘制裁剪的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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