matplotlib图有2个y轴。

时间:2021-03-29 20:19:30

In matplolib for a time line diagram can I set to y-axis different values on the left and make another y-axis to the right with other scale?

在一个时间线图中,我可以将左边的y轴设置为y轴,然后再以其他的比例画出另一个y轴吗?

I am using this:

我用这个:

import matplotlib.pyplot as plt 

plt.axis('normal')
plt.axvspan(76, 76, facecolor='g', alpha=1)
plt.plot(ts, 'b',linewidth=1.5)
plt.ylabel("name",fontsize=14,color='blue')
plt.ylim(ymax=100)
plt.xlim(xmax=100)
plt.grid(True)
plt.title("name", fontsize=20,color='black')
plt.xlabel('xlabel', fontsize=14, color='b')
plt.show()

Can I give 2 y-axis in this plot?

在这个图中我能给出2个y轴吗?

In span selector:

在时间选择器:

 plt.axvspan(76, 76, facecolor='g', alpha=1)

I want to right text to characterize this span for example 'This is span selector' how can I make it?

我想要用正确的文本来描述这个span的特征例如,这是span选择器,我怎么做呢?

1 个解决方案

#1


16  

You want twinx example. The gist if it is:

你想要twinx例子。如果它是:

ax = plt.gca()
ax2 = ax.twinx()

You can then plot to the first axes with

然后你可以画出第一个坐标轴。

ax.plot(...)

and the second with

和第二个

ax2.plot(...)

In your case (I think) you want:

在你的情况下(我认为)你想:

import matplotlib.pyplot as plt 

ax = plt.gca()
ax2 = ax.twinx()
plt.axis('normal')
ax2.axvspan(74, 76, facecolor='g', alpha=1)
ax.plot(range(50), 'b',linewidth=1.5)
ax.set_ylabel("name",fontsize=14,color='blue')
ax2.set_ylabel("name2",fontsize=14,color='blue')
ax.set_ylim(ymax=100)
ax.set_xlim(xmax=100)
ax.grid(True)
plt.title("name", fontsize=20,color='black')
ax.set_xlabel('xlabel', fontsize=14, color='b')
plt.show()

#1


16  

You want twinx example. The gist if it is:

你想要twinx例子。如果它是:

ax = plt.gca()
ax2 = ax.twinx()

You can then plot to the first axes with

然后你可以画出第一个坐标轴。

ax.plot(...)

and the second with

和第二个

ax2.plot(...)

In your case (I think) you want:

在你的情况下(我认为)你想:

import matplotlib.pyplot as plt 

ax = plt.gca()
ax2 = ax.twinx()
plt.axis('normal')
ax2.axvspan(74, 76, facecolor='g', alpha=1)
ax.plot(range(50), 'b',linewidth=1.5)
ax.set_ylabel("name",fontsize=14,color='blue')
ax2.set_ylabel("name2",fontsize=14,color='blue')
ax.set_ylim(ymax=100)
ax.set_xlim(xmax=100)
ax.grid(True)
plt.title("name", fontsize=20,color='black')
ax.set_xlabel('xlabel', fontsize=14, color='b')
plt.show()