Python 在背景图像上散点图以进行数据验证
Python scatter plot over background image for data verification
我正在尝试在 Python 中的背景图像上绘制数据以进行数据验证,即查看我根据自己的数据生成的曲线与我的论文中的曲线有多接近另存为 png 的屏幕截图。
我已经使用 extent
关键字和 imshow
尝试了此处的代码:
Adding a background image to a plot with known corner coordinates 这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
import matplotlib.cbook as cbook
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,1.25,15)
datafile = cbook.get_sample_data('C:\Users\andrew.hills\Desktop\Capture.png')
img = imread(datafile)
plt.scatter(x,y,zorder=1)
plt.imshow(img, zorder=0, extent=[0.0, 10.0, 0.00, 1.25])
plt.show()
我遇到的问题是图形看起来失真了,我认为这是因为轴上的每个像素都设置为 1x1,但我的数据范围在 x 方向上为 0.0-10.0,在 y 方向上为 0.00-1.25方向:
enter image description here
如何更改此设置以使图像不失真?
我想你的意思是你希望你的图像符合你添加它的轴的纵横比,而不是调整轴以具有 1 比 1 的纵横比。如果是这种情况,请尝试将 aspect='auto'
添加到您的 imshow
调用中。
plt.imshow(img, zorder=0, extent=[0.0, 10.0, 0.00, 1.25], aspect='auto')
问题确实是图像通过范围参数获得了新的数据范围,并且图像的纵横比默认为"equal"因此会导致图像失真。
您需要做的是计算一个新的纵横比,将新的数据范围考虑在内。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,1.25,15)
plt.scatter(x,y,zorder=1)
img = plt.imread("house.png")
ext = [0.0, 10.0, 0.00, 1.25]
plt.imshow(img, zorder=0, extent=ext)
aspect=img.shape[0]/float(img.shape[1])*((ext[1]-ext[0])/(ext[3]-ext[2]))
plt.gca().set_aspect(aspect)
plt.show()
我正在尝试在 Python 中的背景图像上绘制数据以进行数据验证,即查看我根据自己的数据生成的曲线与我的论文中的曲线有多接近另存为 png 的屏幕截图。
我已经使用 extent
关键字和 imshow
尝试了此处的代码:
Adding a background image to a plot with known corner coordinates 这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread
import matplotlib.cbook as cbook
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,1.25,15)
datafile = cbook.get_sample_data('C:\Users\andrew.hills\Desktop\Capture.png')
img = imread(datafile)
plt.scatter(x,y,zorder=1)
plt.imshow(img, zorder=0, extent=[0.0, 10.0, 0.00, 1.25])
plt.show()
我遇到的问题是图形看起来失真了,我认为这是因为轴上的每个像素都设置为 1x1,但我的数据范围在 x 方向上为 0.0-10.0,在 y 方向上为 0.00-1.25方向:
enter image description here
如何更改此设置以使图像不失真?
我想你的意思是你希望你的图像符合你添加它的轴的纵横比,而不是调整轴以具有 1 比 1 的纵横比。如果是这种情况,请尝试将 aspect='auto'
添加到您的 imshow
调用中。
plt.imshow(img, zorder=0, extent=[0.0, 10.0, 0.00, 1.25], aspect='auto')
问题确实是图像通过范围参数获得了新的数据范围,并且图像的纵横比默认为"equal"因此会导致图像失真。
您需要做的是计算一个新的纵横比,将新的数据范围考虑在内。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,1.25,15)
plt.scatter(x,y,zorder=1)
img = plt.imread("house.png")
ext = [0.0, 10.0, 0.00, 1.25]
plt.imshow(img, zorder=0, extent=ext)
aspect=img.shape[0]/float(img.shape[1])*((ext[1]-ext[0])/(ext[3]-ext[2]))
plt.gca().set_aspect(aspect)
plt.show()