我想知道如何在matplotlib中使用“extent”使我的背景图像看起来像decent

2024-09-28 22:19:26 发布

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

不管我改变什么样的价值观,它总是扭曲它,或者它太偏左了。你知道吗

举个例子:

Plot with background image

barchart = pd.read_csv('barchart.csv')
df = pd.DataFrame(barchart)
var1 = df['col1'].head(7).tolist()
var2 = df['col2'].head(7).tolist()
sometitle = df['sometitle'][0]
var2 = [ float(x) for x in var2 ]

y_pos = np.arange(len(var1))
datafile = cbook.get_sample_data('/path/to/watch.jpg', asfileobj=False)
im = image.imread(datafile)

plt.imshow(im, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])

barlist = plt.barh(y_pos, var2, align='center', alpha=0.5)
colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
for a, b in zip(range(6), colors):
    barlist[a].set_color(b)
plt.yticks(y_pos, var1)

plt.xlabel('a label', color="green", fontsize=9)
plt.title(sometitle + " " + str(now)) 
plt.show()  

Tags: csvinposdfforpltheadpd
1条回答
网友
1楼 · 发布于 2024-09-28 22:19:26

从文件来看

extent : scalars (left, right, bottom, top), optional, default: None

The location, in data-coordinates, of the lower-left and upper-right corners. If None, the image is positioned such that the pixel centers fall on zero-based (row, column) indices.

所以如果你想把图像放在一个给定的xysize都在数据坐标中,得到im.shape的比率,并用它来缩放。例如

import matplotlib.pyplot as plt
import numpy as np

val = 3+10*np.random.random(7)  
pos = np.arange(7)+.5

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

colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
barlist = ax.barh(pos, val, align='center',alpha=0.5)
for a, b in zip(range(6), colors):
    barlist[a].set_color(b)

im = plt.imread('/path/to/watch.jpg')
x = 4.; y = 0.; size = 7.; xyratio = im.shape[1]/im.shape[0]
ax.imshow(im, zorder=0, extent=[x, x+size , y, y+size*xyratio])

ax.set_xlim([0.,np.max(val)+1.])
ax.set_ylim([0.,np.max(pos)+1.])

plt.show()

看起来像是

enter image description here

注意,还有一个问题是图像周围的空白会导致它看起来远离范围。你知道吗

您也可以执行类似于set aspect="equal"的操作,但必须删除extents。你知道吗

相关问题 更多 >