0

I want to make a multi-lines graph from a pandas dataframe on data that are in groups based on the values of a coloumn. The data here are from a api

import pandas as pd
import numpy as np
import calendar
import requests
import json

r =  requests.get('http://data.unhcr.org/api/stats/mediterranean/monthly_arrivals_by_location.json')
js = r.json()
df = pd.DataFrame.from_records(js)

dfTop10 =  df[['location','value']].\
groupby(['location']).sum().sort_values(['value'], ascending=[0])[1:5].reset_index()

grData  =  df[['year','month','location','value']].loc[df['location'].\
isin(dfTop10.location)].groupby(['location','year','month'])['value'].sum().reset_index()

grData['time'] = pd.to_datetime(df.year*10000+df.month*100+1,format='%Y%m%d')

grData= grData[['location','time','value']]

grData.groupby('location').plot()

This code produces 10 different plots while I want to be in the same image and the group to be shown as different colours. Can anyone help?

1
  • So you want a line for each City? Where the x and y axes are time and value? Commented Jun 25, 2017 at 20:44

1 Answer 1

1

This isn't pretty, but I think it works:

in place of that last line (the groupby line) you could do this:

from matplotlib import pyplot as plt
plt.figure(figsize=(15,5))

for city in set(grData['location']):
    df  = grData[grData['location'] == city]
    plt.plot(df['time'], df['value'])

But I'm sure there is a cooler way to do it.

To add a legend to the graph, add a label= parameter to each plt.plot and then create the legend at the end:

. . .
for city in set(grData['location']):
    df  = grData[grData['location'] == city]
    plt.plot(df['time'], df['value'], label=city)

plt.legend()
Sign up to request clarification or add additional context in comments.

1 Comment

It works, One more question how can I add labels based on the name of the location?

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.