I have a 2D array and I use this data to make a plot, like this:
data = [[2.01756016, 2.83041846, 3.81709531, 4.98948707, 6.2480729],
[2.01756016, 2.59428527, 3.42083514, 4.15525314, 4.87254428],
[2.01756016, 2.47796649, 2.95297856, 3.37313728, 3.66131579],
[2.01756016, 2.24718239, 2.56393939, 2.70463483, 2.65250443]]
fig, ax = plt.subplots(figsize=(6, 6))
sidex = np.linspace(0.875, 2.125, 6)
sidey = np.linspace(5, 45, 5)
x, y = np.meshgrid(sidex, sidey)
z = [[data[i][j] for j in range(len(data[0]))] for i in range(len(data))]
plt.pcolormesh(x, y, z)
plt.xticks([1, 1.25, 1.5, 1.75, 2])
plt.yticks([10, 20, 30, 40])
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Now I am trying to change the y-axis
make the y-axis from Y to Y/10
create second y-axis at the right-hand side of the plot: Y/100
Like the figure below. How can I achieve this?
I try to change plt.yticks([10, 20, 30, 40])
into plt.yticks([1, 2, 3, 4])
, but the result is not what I want.
You can achieve it using twinx()
. I recommend to use ax.set_yticks
and ax.set_yticklabels
for more control, but it would be possible to use plt.yticks(ticks=ticks, labels=labels)
, too.
EDIT : I added a colorbar to the plot. When creating a colorbar, you can specify a mappable
(the object for which the colors should be matched) as the first argument. For this, I assigned the colormesh to a variable for later reuse ( image = ax.pcolormesh(x, y, z)
).
data = [[2.01756016, 2.83041846, 3.81709531, 4.98948707, 6.2480729],
[2.01756016, 2.59428527, 3.42083514, 4.15525314, 4.87254428],
[2.01756016, 2.47796649, 2.95297856, 3.37313728, 3.66131579],
[2.01756016, 2.24718239, 2.56393939, 2.70463483, 2.65250443]]
fig, ax = plt.subplots(figsize=(6, 6))
ax2 = ax.twinx()
sidex = np.linspace(0.875, 2.125, 6)
sidey = np.linspace(5, 45, 5)
x, y = np.meshgrid(sidex, sidey)
z = [[data[i][j] for j in range(len(data[0]))] for i in range(len(data))]
image = ax.pcolormesh(x, y, z)
ax.set_xticks([1, 1.25, 1.5, 1.75, 2])
ax.set_yticks([10, 20, 30, 40])
ax.set_yticklabels([1, 2, 3, 4])
ax2.set_yticks([10, 20, 30, 40])
ax2.set_yticklabels([10, 20, 30, 40])
ax2.set_ylim(ax.get_ylim())
fig.colorbar(image, pad=0.1)
ax.set_xlabel('X')
ax.set_ylabel('Y/10')
ax2.set_ylabel('Y')
plt.tight_layout()
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.