# 如何在matplotlib imshow等高线图的顶部显示数据点？

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

x = np.linspace(-0.5, 2.0, 101)
y = np.linspace(-0.5, 2.0, 101)
z = np.zeros((101, 101))
E = 0.0
for i in range(len(x)):
for j in range(len(y)):
z[i,j] = -max(y[j]+0.2+E, 0.5-x[i], 0)

x_new = np.array([1.1168189, 0.8381589, 1.3312789, -0.2149011])
y_new = np.array([1.7571379, 1.5555579, 1.9138179, 0.7912879])
z_new = []
for k, l in zip(x_new, y_new):
#print (k, l, -max(l+0.2+E, 0.5-k, 0)) # z_new = -max(l+0.2+eU, 0.5-k, 0) calculated for some random x_new and y_new
z_new.append(-max(l+0.2+E, 0.5-k, 0)) # I would like to see these z_new points on the contour plot for corresponding x_new and y_new

fig, ax = plt.subplots()
ms = plt.imshow(z.T, cmap='plasma', vmin=-2.5, vmax=0, origin='lower', interpolation='none', extent=[-0.5,2.0,-0.5,2.0])
ax.set_xlabel('x', fontsize=16, fontname = "Helvetica")
ax.set_ylabel('y', fontsize=16, fontname = "Helvetica")
cbar = plt.colorbar(ms)
cbar.ax.tick_params(labelsize=10, direction='out')
cbar.set_label('z', fontsize=16, fontname = "Helvetica")
#plt.savefig('test.pdf')
plt.xticks(fontname = "Helvetica", fontsize=12)
plt.yticks(fontname = "Helvetica", fontsize=12)
plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

x = np.linspace(-0.5, 2.0, 101)
y = np.linspace(-0.5, 2.0, 101)
z = np.zeros((101, 101))
E = 0.0
for i in range(len(x)):
for j in range(len(y)):
z[i,j] = -max(y[j]+0.2+E, 0.5-x[i], 0)

x_new = np.array([1.1168189, 0.8381589, 1.3312789, -0.2149011])
y_new = np.array([1.7571379, 1.5555579, 1.9138179, 0.7912879])
z_new = []
for k, l in zip(x_new, y_new):
#print (k, l, -max(l+0.2+E, 0.5-k, 0)) # z_new = -max(l+0.2+eU, 0.5-k, 0) calculated for some random x_new and y_new
z_new.append(-max(l+0.2+E, 0.5-k, 0)) # I would like to see these z_new points on the contour plot for corresponding x_new and y_new

fig, ax = plt.subplots()
ms = plt.imshow(z.T, cmap='plasma', vmin=-2.5, vmax=0, origin='lower', interpolation='none', extent=[-0.5,2.0,-0.5,2.0])
ax.set_xlabel('x', fontsize=16, fontname = "Helvetica")
ax.set_ylabel('y', fontsize=16, fontname = "Helvetica")
cbar = plt.colorbar(ms)
cbar.ax.tick_params(labelsize=10, direction='out')
cbar.set_label('z', fontsize=16, fontname = "Helvetica")
#plt.savefig('test.pdf')
plt.xticks(fontname = "Helvetica", fontsize=12)
plt.yticks(fontname = "Helvetica", fontsize=12)

## New code ##
# plt.scatter(x_new, y_new, c=z_new, cmap='plasma', vmin=-2.5, vmax=0, edgecolors='black') #Uncommend this if you want the points circled in black
plt.scatter(x_new, y_new, c=z_new, cmap='plasma', vmin=-2.5, vmax=0)
## End of new code ##

plt.show()
``````

0条评论