如何使用matplotlib从现有的数据数组在python中创建colorplot

2024-09-28 01:30:34 发布

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

我有一些数据已经用python读入numpy数组,每个数组的长度是22500个数据点。我试图用下面的代码创建一个彩色图,但它不起作用。如果有人能给我一些关于我做错了什么的建议,我将不胜感激。在

# - The code starts out with lines which read data from a text file into three separate 
#   python lists.  However, these lines are not necessary for this example so they are
#   being omitted.

# These lines transform the lists into numpy arrays.  Each array contains 22,500 data points
XVal = np.array(Array1)
YVal = np.array(Array2)
ZVal = np.array(Array3)

# - These section attempts to create a 2D color map of the data with the XVal and ZVal arrays
#   being represented as x and y coordinates on the color map and the ZVal array represented
#   as a color on the X and Y coordinates

import pylab

# Create the colormap
pylab.pcolor(XVal,YVal,ZVal)
# Create colorbar
pylab.colorbar()
# Show plot on screen
pylab.show() 

当我运行这段代码时,我得到以下冗长的错误消息

^{pr2}$

Tags: andthe数据代码numpydataonnp
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:34

为了完成,我添加了正确的代码行来解决我的问题。对于如此大的数据集,它需要imshow和覆盖数据的网格,这需要在原始X、Y、Z坐标和网格网格X、Y、Z坐标之间进行插值。在

XVal = np.array(XVal); YVal = np.array(YVal); ZVal = np.array(ZVal)
Tally = np.array(Tally); Error = np.array(Error)

import pylab as plt
from matplotlib.colors import LogNorm
import matplotlib.cm as cm
import scipy.interpolate

# Sets up a mesh grid over which data points will be plotted
xi, yi = np.linspace(XVal.min(),XVal.max(),100), np.linspace(YVal.min(),YVal.max(),100)
xi, yi = np.meshgrid(xi,yi)

# Function to interpolate data points on mesh grid
doseinterp = scipy.interpolate.Rbf(XVal, YVal, Tally, function='linear')

# - Uses the above function to interpolate data points at mesh grid locations
#   from MCNP Mesh Tally data
zi  = doseinterp(xi,yi)

# Plots a heat map of Dose Rate over the mesh grid
fig,plt = plt.subplots()
plt.set_title('Z = 0 cm',fontsize=20)
plt.set_xlabel('X (cm)',fontsize=18)
plt.set_ylabel('Y (cm)',fontsize=18)
img1 = plt.imshow(zi,norm=LogNorm(vmin=Tally.min(),vmax=Tally.max()),extent=[XVal.min(),XVal.max(), \
                YVal.min(),YVal.max()])
cb = fig.colorbar(img1)
cb.set_label('Magnitude')
fig.savefig('C:\Users\jawebb\Desktop\Dose.png')

plt.clear()

相关问题 更多 >

    热门问题