P中的Matplotlib Pyplot徽标/图像

2024-05-13 06:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正努力在matplotlib中实现一个简单的目标。。。我想把一个小的标志或指标在我的图表右下角,而不改变轴或真正的数据显示。这是我的代码:

fig = plt.figure()
plt.rcParams.update({'font.size': 15})

img = plt.imread('./path/to/image.png')
ax1 = fig.add_subplot(111)
ax1.yaxis.tick_left()
ax1.tick_params(axis='y', colors='black', labelsize=15)
ax1.tick_params(axis='x', colors='black', labelsize=15)

plt.grid(b=True, which='major', color='#D3D3D3', linestyle='-')

plt.scatter([1,2,3,4,5],[5,4,3,2,1], alpha=1.0)

plt.autoscale(enable=True, axis=u'both')

fig.savefig('figure.png')

我的输出如下。

现在这是将照片放在整个图形上——我希望它缩放到宽度和高度的20%(如果可能的话),并锚定到右下角。这也破坏了我的轴,因为在这个输出中,我应该在x&y的0-100范围内。任何解决这个问题的办法,缩放是个大问题。

编辑1:我已经尝试了下面的解决方案,并在这里链接了一些问题。问题是依赖于传递给extentimshow()变量,在引入新数据时效果不好。例如,绘制来自数据帧的散点图,可以是0..1000和50..100,但使用范围不会显示标签,否则位置将关闭。

Edit2:使用fig.get_size_inches()获取图形长度并将变量传递给extent似乎有一些进展。显然,所有matplotlib图的计算都是通过英寸完成的,因此这可能是一个很有前途的线索。

enter image description here


Tags: 数据truesizepngmatplotlibfigpltparams
2条回答

以下是对Kirubaharan J答案的改编,但将徽标的位置调整到图形的范围内(但徽标本身的纵横比没有保留)

import matplotlib.image as image
import matplotlib.pyplot as plt

im =image.imread('debian-swirl.png')
fig, ax = plt.subplots()
ax.yaxis.tick_left()
ax.tick_params(axis='y', colors='black', labelsize=15)
ax.tick_params(axis='x', colors='black', labelsize=15)
ax.grid(b=True, which='major', color='#D3D3D3', linestyle='-')
ax.scatter( [100,90,89,70], [55, 23,76,29], alpha=1.0)

plt.autoscale(enable=True, axis=u'both')

xrng=plt.xlim()
yrng=plt.ylim()
scale=.2 #the image takes this fraction of the graph
ax.imshow(im,aspect='auto',extent=(xrng[0],xrng[0] + scale*(xrng[1]-xrng[0]), yrng[0], yrng[0] + scale*(yrng[1]-yrng[0]) ), zorder=-1)
plt.xlim(xrng)
plt.ylim(yrng)

plt.show()
import matplotlib.image as image
import matplotlib.pyplot as plt

im = image.imread('debian-swirl.png')
fig, ax = plt.subplots()
ax.imshow(im, aspect='auto', extent=(0.4, 0.6, .5, .7), zorder=-1)
ax.yaxis.tick_left()
ax.tick_params(axis='y', colors='black', labelsize=15)
ax.tick_params(axis='x', colors='black', labelsize=15)
ax.grid(b=True, which='major', color='#D3D3D3', linestyle='-')
ax.scatter([1,2,3,4,5],[5,4,3,2,1], alpha=1.0)
plt.show()

enter image description here

我在左下角添加了一个png文件。调整“范围”参数以设置徽标位置。

类似于:Scale image in matplotlib without changing the axis

相关问题 更多 >