Skip to main content
 首页 » 编程设计

python之矩阵的某些值未出现在 Matplotlib 的图中

2024年10月01日8虾米姐

我从 CSV 创建了一个空的引用矩阵,将 (x,y) 定位为矩阵上的一个位置(并将它们打印出来),并将 100 指定为矩阵上的那个位置。每个 x 都是 ref_mass pandas 系列中的值。

ref_df = pd.read_csv(ref_file) 
reference = np.zeros(shape=(1201,len(ref_df))) 
ref_mass = ref_df["mass"] 
 
for i, mass in enumerate(ref_mass): 
  print ref_mass[i].astype(int) - 300, i # print (x,y) 
  reference[(ref_mass[i].astype(int) - 300),i] = 100 

每个 (x,y) 都被正确打印出来。但是,某些 (x,y) 的图中没有任何值。这里出了什么问题?我检查了引用矩阵,它正确地在每一列中都有 100。

(x,y):

547 0 
265 1 
124 2 
39 3 
509 4 # shown 
240 5 # shown 
105 6 
24 7 
355 8 
137 9 
28 10 # shown 
394 11 
163 12 
48 13 
347 14 
132 15 # shown 
24 16 

剧情:

剧情代码:

if __name__ == '__main__': 
  from mpl_toolkits.mplot3d import Axes3D 
  import matplotlib.pyplot as plt 
  import matplotlib 
  matplotlib.matplotlib_fname() 
 
  plt.ylabel('m/z') 
  plt.xlabel('Peptides') 
 
  plt.imshow(reference, aspect='auto', cmap='terrain') 
  plt.colorbar() 
  plt.tight_layout() 
 
  plt.show() 

请您参考如下方法:

最终图像中的每个像素代表 3 个或更多数据点。然后渲染器必须决定从 2 次蓝色、1 次白色中选择哪种颜色映射到该像素。从统计上看,蓝色的频率是白色的两倍,因此 66% 的数据点未显示。

3个像素的数量来自粗略计算:您的图像有480个像素(您可以在图片程序中找到或通过计算数字大小* dpi 来找到)。您有 1200 个数据点(从轴上看)。您在两端都有约 10% 的 margin ;所以最终图像中每个像素大约有 1200/(0.8*480) = 3.1 个数据点。

imshow插值

您可以使用 interpolation on the image使这些像素出现,例如

plt.imshow(..., interpolation="sinc") 

然而,结果在视觉上可能不是很吸引人。

改变分辨率

您还可以确保最终绘图中每个数据点恰好包含一个像素。 IE。对于 1200 像素和 100 的 dpi,你可以做

m = 0.1 
plt.figure(figsize=(8, (1+2.*m)*1200./dpi )) 
plt.subplots_adjust(bottom=m, top=1.-m) 
plt.imshow(...) 

过滤数据

另一种选择是更改数据,使一个像素沿 y 方向变为三个像素。

import matplotlib.pyplot as plt 
import numpy as np; np.random.seed(1) 
import scipy.ndimage.filters as filters 
 
a = np.zeros((1200, 16)) 
for i in range(16): 
    a[i*70+21, i] = 1 
 
kernel = np.array([[0.,1.,0.], 
                   [0.,1.,0.], 
                   [0.,1.,0.]]) 
anew = filters.convolve(a,kernel,mode='constant', cval=0) 
 
im = plt.imshow(anew, aspect="auto") 
plt.colorbar(im) 
 
plt.show() 

画线

import matplotlib.pyplot as plt 
import numpy as np 
 
a = np.zeros((1200, 16)) 
 
im = plt.imshow(a, aspect="auto", vmin=0, vmax=1) 
plt.colorbar(im) 
 
for i in range(16): 
    plt.plot([i-.5, i+.5], [i*70+21,i*70+21], color=im.cmap(1.)) 
 
plt.show()