Python 如何使用matplotlib设置所有四个轴

Python 如何使用matplotlib设置所有四个轴,python,matplotlib,Python,Matplotlib,我想画一幅像这样的图,上轴和右轴有不同的标签和记号,有人能帮我吗?你应该使用twinx和twiny函数,看看要双倍两个轴,你必须使用ax1.twinx().twiny() 这里有一个例子: # Create some mock data x1 = np.arange(0, 10, 1) y1 = [random.randint(1,5) for n in x1] #print(x1,y1) x2 = np.arange(0, 100, 10) y2 = [random.randint(10,5


我想画一幅像这样的图,上轴和右轴有不同的标签和记号,有人能帮我吗?

你应该使用
twinx
twiny
函数,看看要双倍两个轴,你必须使用
ax1.twinx().twiny()

这里有一个例子:

# Create some mock data
x1 = np.arange(0, 10, 1)
y1 = [random.randint(1,5) for n in x1]
#print(x1,y1)

x2 = np.arange(0, 100, 10)
y2 = [random.randint(10,50) for n in x2]
#print(x2,y2)

fig, ax1 = plt.subplots()

ax1.set_xlabel('x1', color='red')
ax1.set_ylabel('y1', color='red')
ax1.plot(x1, y1, color='red')
ax1.tick_params(axis='both', labelcolor='red')

ax2 = ax1.twinx().twiny() #here is the trick!

ax2.set_xlabel('x2', color='blue')
ax2.set_ylabel('y2', color='blue')
ax2.plot(x2, y2, color='blue')
ax2.tick_params(axis='both', labelcolor='blue') #y2 does not get blue... can't yet figure out why

plt.show()
结果如下:


由于两个数据集完全独立,这里可能不使用双轴。相反,只需使用两个不同的轴即可

import numpy as np
import matplotlib.pyplot as plt

# Create some mock data
x1 = np.linspace(0,1,11)
y1 = np.random.rand(11)
x2 = np.linspace(1,0,101)
y2 = np.random.rand(101)*20+20


fig, ax1 = plt.subplots()
ax2 = fig.add_subplot(111, label="second axes")
ax2.set_facecolor("none")

ax1.set_xlabel('x1', color='red')
ax1.set_ylabel('y1', color='red')
ax1.plot(x1, y1, color='red')
ax1.tick_params(colors='red')

ax2.set_xlabel('x2', color='blue')
ax2.set_ylabel('y2', color='blue')
ax2.plot(x2, y2, color='blue')
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top') 
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(colors='blue')

for which in ["top", "right"]:
    ax2.spines[which].set_color("blue")
    ax1.spines[which].set_visible(False)
for which in ["bottom", "left"]:
    ax1.spines[which].set_color("red")
    ax2.spines[which].set_visible(False)

plt.show()

检查文档!绘图还可以,但我不知道如何在第二个Y轴上固定颜色和标签。如果有人知道怎么做,请评论!构造
ax1.twinx().twiny()
不是很有用,因为它隐藏了现在有3个轴的事实。使用
ax2=ax1.twinx();ax3=ax2.twiny()
并根据您的喜好设置
ax2
ax3
的格式。@importantanceofbeingernest然后在哪里绘图?在ax2或ax3上?这有点让人困惑,你能用一个例子来添加答案吗?你可以像在这里一样在
ax3
上绘图,但你将有一个
ax2
的句柄来格式化或着色它。因为我个人不会用双轴来解决这种问题(不需要双轴,两条曲线都是完全独立的),所以我不会提供任何这样的答案。