python中x轴和y轴比例不同的一个图中的两个(或多个)图

2024-10-07 12:15:10 发布

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

我想要一个轴上有3个图形对象,例如:

#example x- and y-data
x_values1=[1,2,3,4,5]
y_values1=[1,2,3,4,5]

x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]

x_values3=[150,200,250,300,350]
y_values3=[10,20,30,40,50]


#make axes
fig=plt.figure()
ax=fig.add_subplot(111)

现在我想把这三个数据集都添加到ax中。但它们不应该共享任何x轴或y轴(因为不同的尺度,一个比另一个小得多)。我需要像ax.twinx()、ax.twiny()这样的东西,但是x轴和y轴都需要独立。

我想这样做,因为我想把两个附加的图(和第三个,类似于第二个)放在一个图中(“把它们放在一起”)。 Plot1Plot2

然后我将第二个绘图的x/y-标签(和/或记号,限制)放在右/上,另一个绘图的x/y-限制放在左/下。我不需要三个x/y标签。阴谋。

我该怎么做?


Tags: and对象图形绘图datamakeexamplefig
2条回答

我们的想法是在同一个位置创建三个子块。为了确保它们被识别为不同的图,它们的属性需要不同——而实现这一点的最简单方法就是提供不同的标签ax=fig.add_subplot(111, label="1")

剩下的只是调整所有的轴参数,这样得到的图看起来很吸引人。 设置所有参数有点麻烦,但下面的操作应该可以满足您的需要。

enter image description here

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]

x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]

x_values3=[150,200,250,300,350]
y_values3=[10,20,30,40,50]


fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)

ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")

ax2.scatter(x_values2, y_values2, color="C1")
ax2.xaxis.tick_top()
ax2.yaxis.tick_right()
ax2.set_xlabel('x label 2', color="C1") 
ax2.set_ylabel('y label 2', color="C1")       
ax2.xaxis.set_label_position('top') 
ax2.yaxis.set_label_position('right') 
ax2.tick_params(axis='x', colors="C1")
ax2.tick_params(axis='y', colors="C1")

ax3.plot(x_values3, y_values3, color="C3")
ax3.set_xticks([])
ax3.set_yticks([])

plt.show()

您还可以将数据标准化,使其共享相同的限制,然后“手动”绘制所需的第二个比例的限制。 此函数将数据标准化到第一组点的限制:

def standardize(data):
    for a in range(2):
        span = max(data[0][a]) - min(data[0][a])
        min_ = min(data[0][a])
        for idx in range(len(data)):
            standardize = (max(data[idx][a]) - min(data[idx][a]))/span
            data[idx][a] = [i/standardize + min_ - min([i/standardize 
                            for i in data[idx][a]]) for i in data[idx][a]]
    return data

然后,绘制数据很容易:

import matplotlib.pyplot as plt
data = [[[1,2,3,4,5],[1,2,2,4,1]], [[-1000,-800,-600,-400,-200], [10,20,39,40,50]], [[150,200,250,300,350], [10,20,30,40,50]]]
limits = [(min(data[1][a]), max(data[1][a])) for a in range(2)]

norm_data = standardize(data)

fig, ax = plt.subplots()

for x, y in norm_data:
    ax.plot(x, y)

ax2, ax3 = ax.twinx(), ax.twiny()
ax2.set_ylim(limits[1])
ax3.set_xlim(limits[0])

plt.show()

因为所有数据点都有第一组点的限制,所以我们可以将它们绘制在同一个轴上。然后,使用所需的第二个x和y轴的限制,我们可以设置这两个轴的限制。

Rsulting plot

相关问题 更多 >