matplotlib:对齐y轴的标签堆叠散点图标签、matplotlib、散点图

2023-09-12 21:26:36 作者:跑赢你自己!

在情节波纹管我有两个散点图具有不同数量的规模,所以他们的Y轴标签不对齐。有没有什么办法可以强制在y轴标签的水平对齐方式?

In the plot bellow i have two scatter plots which have different number scale, so their Y-axis labels are not aligned. Is there any way I can force the horizontal alignment in the y-axis labels?

import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)
data1 = [random.random() for i in range(10)]
data2 = [random.random()*1000 for i in range(10)]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

ax = fig.add_subplot(gs[0])
ax.plot(data1)
ax.set_ylabel(r'Label One', size =16)

ax = fig.add_subplot(gs[1])
ax.plot(data2)
ax.set_ylabel(r'Label Two', size =16)

plt.show()

推荐答案

您可以使用set_label_coords方法。

You can use the set_label_coords method.

import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)
data1 = [random.random() for i in range(10)]
data2 = [random.random()*1000 for i in range(10)]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

ax = fig.add_subplot(gs[0])
ax.plot(data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

ax = fig.add_subplot(gs[1])
ax.plot(data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)