[英]How to Make a Plot with Two Different Y-axis in Python
I have a 2D array and I use this data to make a plot, like this:我有一个二维数组,我使用这些数据来制作 plot,如下所示:
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现在我正在尝试更改 y 轴
make the y-axis from Y to Y/10使y轴从Y到Y/10
create second y-axis at the right-hand side of the plot: Y/100在 plot 的右侧创建第二个 y 轴: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.我尝试将
plt.yticks([10, 20, 30, 40])
更改为plt.yticks([1, 2, 3, 4])
,但结果不是我想要的。
You can achieve it using twinx()
.您可以使用
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.我建议使用
ax.set_yticks
和ax.set_yticklabels
进行更多控制,但也可以使用plt.yticks(ticks=ticks, labels=labels)
。
EDIT : I added a colorbar to the plot.编辑:我在 plot 中添加了一个颜色条。 When creating a colorbar, you can specify a
mappable
(the object for which the colors should be matched) as the first argument.创建颜色条时,您可以指定一个
mappable
(colors 应匹配的 object)作为第一个参数。 For this, I assigned the colormesh to a variable for later reuse ( image = ax.pcolormesh(x, y, z)
).为此,我将 colormesh 分配给一个变量以供以后重用(
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.