简体   繁体   English

在matplotlib中用两个Y轴(两个单位)绘制单个数据

[英]Plot single data with two Y axes (two units) in matplotlib

I'm trying to plot a single time series, but want to represent it in two units on left and right axes. 我正在尝试绘制单个时间序列,但想要在左右轴上以两个单位表示它。 Here's what I have done so far. 这是我到目前为止所做的。

fig, ax1 = plt.subplots()
t = np.arange(1,50,1)
s1 = np.sin(t)*20000+40000 #synthetic ts, but closer to my data 
ax1.plot(t, s1, 'b-')

ax1.set_xlabel('time')
ax1.set_ylim(20000,70000)
ax1.set_ylabel('km3/year')

km3yearToSv=31.6887646*(1/1e6)

ax2 = ax1.twinx()
s2 = s1*km3yearToSv
ax2.plot(t, s2, 'b-')
ax2.set_ylim(20000*km3yearToSv,70000*km3yearToSv)
ax2.set_ylabel('Sv')

在此输入图像描述

By adjusting the ylim(), I can get it to seem as a single line, but some aliasing can be seen. 通过调整ylim(),我可以将它看作单行,但可以看到一些别名。 I would prefer if I don't have to plot the data twice. 如果我不必两次绘制数据,我更愿意。

Any suggestions? 有什么建议?

UPDATE: Thanks, askewchan, for the perfect solution! 更新:谢谢,askewchan,完美的解决方案!

There is no need to plot it twice, this much should give you the result you want: 没有必要绘制两次,这应该给你想要的结果:

ax2 = ax1.twinx()
ax2.set_ylim(20000*km3yearToSv, 70000*km3yearToSv)
ax2.set_ylabel('Sv')

A more robust way to do it is to first extract the limits of the plot (in case you change them, and they're no longer 20000 and 70000 , or you want the plot to be able to automatically adjust the limits: 一个更健壮的方法是首先提取绘图的限制(如果你更改它们,它们不再是2000070000 ,或者你希望绘图能够自动调整限制:

ax2 = ax1.twinx()
mn, mx = ax1.get_ylim()
ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv)
ax2.set_ylabel('Sv')

一个情节

Altogether, with some other small tweaks: 总而言之,还有其他一些小调整:

import numpy as np
import matplotlib.pyplot as plt

mean, amp = 40000, 20000
t = np.arange(50)
s1 = np.sin(t)*amp + mean #synthetic ts, but closer to my data 

fig, ax1 = plt.subplots()
ax1.plot(t, s1, 'b-')

ax1.set_xlabel('time')
mn, mx = ax1.set_ylim(mean-amp, mean+amp)
ax1.set_ylabel('km$^3$/year')

km3yearToSv = 31.6887646e-6

ax2 = ax1.twinx()
ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv)
ax2.set_ylabel('Sv')

one small error in code above: 上面代码中的一个小错误:

mn, mx = ax2.get_ylim()

should be: 应该:

mn, mx = ax1.get_ylim()

to scale new secondary axis based on original. 根据原始尺度缩放新的辅助轴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM