简体   繁体   English

在matplotlib子图中添加一行

[英]add a line to matplotlib subplots

I would like to do a subplot of two figures with matplotlib and add a horizontal line in both. 我想用matplotlib做两个图的子图,并在两个图中添加一条水平线。 This is probably basic, but I don't know how to specify that one of the lines should be drawn in the first figure, they both end up in the last one. 这可能是基本的,但是我不知道如何指定应该在第一幅图中绘制其中的一条线,它们都最后一条线。 eg 例如

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 does not have "ax" as an argument, as the pandas plot function does. axhline不像熊猫图函数那样将“ ax”作为参数。 So this would work: 所以这可以工作:

l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])

I read the examples in matplotlib and I tried with this other option that does not work either (probably for good reasons) 我阅读 matplotlib中的示例 ,并尝试了另一种也不起作用的选项(可能有充分的理由)

axes[0].plt.axhline(0.5,color='black',ls='--')

How should I do to draw lines in subplots? 如何在子图中绘制线条? Ideally with a legend Thanks! 理想情况下带有图例谢谢!

with the help of @Nick Becker I answered my own "syntax" question. 在@Nick Becker的帮助下,我回答了我自己的“语法”问题。

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')

水平线的子图

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

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