1

I have the following pandas dataframe

test = pd.DataFrame({'cities':['A','B','A','B','A','B',],
               'date':['2016-9-1','2016-9-1','2016-9-2','2016-9-2','2016-9-3','2016-9-3'],
               'count':[10,20,30,40,50,60]})

And I'd like to plot two scatter plots, one for city 'A' and one for city 'B'. In each plot, x-axis is date, and y-axis is count.

I tried a bit, but the code is so ugly that I am shy from posting it up. Would appreciate somebody to help with some elegant way to do this.

Thank you.

1
  • 2
    Don't be shy and show us: nothing is uglier than asking for code without sharing its own Commented Sep 6, 2016 at 4:32

1 Answer 1

1

Setup

test = pd.DataFrame({'cities':['A','B','A','B','A','B',],
               'date':['2016-9-1','2016-9-1','2016-9-2','2016-9-2','2016-9-3','2016-9-3'],
               'count':[10,20,30,40,50,60]})

test.date = pd.to_datetime(test.date)

Solution

import matplotlib.pyplot as plt


gb = test.groupby('cities')

fig, axes = plt.subplots(gb.ngroups)
for i, (name, df) in enumerate(gb):
    ax = axes[i]
    ax.scatter(df['date'].values, df['count'].values)
    ax.set_title(name)

fig.autofmt_xdate()
fig.tight_layout()

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

I think you first need to convert date column to datetime with pd.to_datetime because without that it causes an error with plotting.
@AntonProtopopov I do! I forgot that part of the copy/paste... thx
I'm trying this testA=test[test.cities=='A'] and then testA.plot(x=testA['date'],y=testA['count'],kind='scatter') and I'm getting this error: KeyError: "['2016-09-01T00:00:00.000000000' '2016-09-02T00:00:00.000000000'\n '2016-09-03T00:00:00.000000000'] not in index". Can you explain to me what I'm doing wrong here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.