jim jarnac
jim jarnac

Reputation: 5152

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

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.

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.

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?

Upvotes: 1

Views: 2460

Answers (1)

Elegant Code
Elegant Code

Reputation: 690

This should do it (just add fig, ax = plt.subplots() in the beginning):

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

enter image description here

Upvotes: 4

Related Questions