循环内的 matplotlib twinx [英] matplotlib twinx inside a loop

查看:22
本文介绍了循环内的 matplotlib twinx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,在特定条件下(例如发生3次),我想用twinx绘制两个数据集,所以例如最后我在左y上有3个图,在右y上有3个图.当我使用通常的twinx时,循环为right-y取不正确的值.我应该如何修改此示例代码以使其正确?非常感谢!

I have a loop which for a certain condition (occurs e.g 3 times), I'd like to plot two dataset with twinx, so e.g at the end I have 3 plots on left-y and 3 plots on right-y. When I use the usual twinx, the loop takes incorrect values for right-y. How should I modify this example code to get them correct? Thank you very much!

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,10,100)
A=5

fig,ax=plt.subplots()

for i in range(0,10):
  A=i**2
  if(i%3==0):
    ax.plot(x,A*np.sin(x),'-ro')
    ax2=ax.twinx()
    ax2.plot(x,A*x,'-bp')
plt.show()

这是输出.

推荐答案

您需要将"ax2"定义移到循环外(请参见下文).但是,这产生了七个地块,四个在左边,三个在右边.您需要更新if"条件.

You need to move your "ax2" definition outside the loop (see below). However, this makes seven plots, four on left, three on right. You need to update your "if" condition.

[![import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(0,10,100)
A=5

fig,ax=plt.subplots()
ax2=ax.twinx()

for i in range(0,10):
  A=i**2
  if(i%3==0):
    ax.plot(x,A*np.sin(x),'-ro')
    ax2.plot(x,A*x,'-bp')
plt.show()][1]][1]

这篇关于循环内的 matplotlib twinx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆