简体   繁体   English

在熊猫中,将散点图添加到线图

[英]in pandas , add scatter plot to line plot

I am trying to add a scatter plot to a line plot by using plandas plot function (in jupyter notebook).我正在尝试使用 plandas plot 函数(在 jupyter notebook 中)将散点图添加到线图。

I have tried the following code :我尝试了以下代码:

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

# plot the line 
a = pd.DataFrame({'a': [3,2,6,4]})
ax = a.plot.line()

# try to add the scatterplot
b = pd.DataFrame({'b': [5, 2]})
plot = b.reset_index().plot.scatter(x = 'index', y = 'b', c ='r', ax = ax)
plt.show()

I also checked the following various SO answers but couldn't find the solution.我还检查了以下各种 SO 答案,但找不到解决方案。

If anytone can help me, that ould be very appreciated.如果任何人可以帮助我,那将不胜感激。


EDIT:编辑:

somehow the accepted answers works, but i realise that in my case the reason it was not working might have to do with the fact i was using datetime.以某种方式接受的答案有效,但我意识到在我的情况下,它不起作用的原因可能与我使用 datetime 的事实有关。

like in this code, i cant see the red dots...就像在这段代码中,我看不到红点...

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
%matplotlib inline

fig, ax = plt.subplots()
# plot the line 
a = pd.DataFrame({'a': [3,2,6,4]}, index = pd.date_range(dt(2019,1,1), periods = 4))
plot = a.plot.line(ax = ax)

# try to add the scatterplot
b = pd.DataFrame({'b': [5, 2]}, index = [x.timestamp() for x in pd.date_range(dt(2019,1,1), periods = 2)])
plot = b.reset_index().plot.scatter(x = 'index', y = 'b', c ='r', ax = ax)
plt.show()

Any idea whats wrong here?知道这里有什么问题吗?

This should do it (just add fig, ax = plt.subplots() in the beginning):这应该这样做(只需在开头添加fig, ax = plt.subplots() ):

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots()

# plot the line 
a = pd.DataFrame({'a': [3,2,6,4]})
a.plot.line(ax=ax)

# try to add the scatterplot
b = pd.DataFrame({'b': [5, 2]})
plot = b.reset_index().plot.scatter(x = 'index', y = 'b', c ='r', ax = ax)
plt.show()

Please let me know if you need anymore help.如果您需要更多帮助,请告诉我。

Edit: This will work for datetimes:编辑:这适用于日期时间:

import matplotlib.pyplot as plt
from datetime import datetime as dt
# %matplotlib inline

fig, ax = plt.subplots()
# plot the line 
a = pd.DataFrame({'a': [3,2,6,4]}, index = pd.date_range(dt(2019,1,1), periods = 4))
plot = plt.plot_date(x=a.reset_index()['index'], y=a['a'], fmt="-")

# try to add the scatterplot
b = pd.DataFrame({'b': [5, 2]}, index = pd.date_range(dt(2019,1,1), periods = 2))
plot = plt.scatter(x=b.reset_index()['index'], y=b['b'], c='r')
plt.show()````

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

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