向 matplotlib 子图添加一行
add a line to matplotlib subplots
我想用 matplotlib 绘制两个图形的子图,并在两个图形中添加一条水平线。这可能是基本的,但我不知道如何指定在第一个图中绘制其中一条线,它们都在最后一个图中结束。例如
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')
f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--')
l2.set_label('l2')
plt.legend()
axhline 不像 pandas 绘图函数那样将 "ax" 作为参数。所以这会起作用:
l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])
我在 matplotlib 中阅读了 the examples,我尝试了另一个也不起作用的选项(可能出于充分的原因)
axes[0].plt.axhline(0.5,color='black',ls='--')
子图中画线怎么办?最好有图例谢谢!
在@Nick Becker 的帮助下,我回答了我自己的 "syntax" 问题。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')
axes[0].legend(loc='best')
f2= s1.plot(ax=axes[1],label='s2')
l2=axes[1].axhline(0.5,color='black',ls='--')
l2.set_label('l2')
axes[1].legend(loc='best')
我想用 matplotlib 绘制两个图形的子图,并在两个图形中添加一条水平线。这可能是基本的,但我不知道如何指定在第一个图中绘制其中一条线,它们都在最后一个图中结束。例如
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')
f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--')
l2.set_label('l2')
plt.legend()
axhline 不像 pandas 绘图函数那样将 "ax" 作为参数。所以这会起作用:
l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])
我在 matplotlib 中阅读了 the examples,我尝试了另一个也不起作用的选项(可能出于充分的原因)
axes[0].plt.axhline(0.5,color='black',ls='--')
子图中画线怎么办?最好有图例谢谢!
在@Nick Becker 的帮助下,我回答了我自己的 "syntax" 问题。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')
axes[0].legend(loc='best')
f2= s1.plot(ax=axes[1],label='s2')
l2=axes[1].axhline(0.5,color='black',ls='--')
l2.set_label('l2')
axes[1].legend(loc='best')