Nhyi
Nhyi

Reputation: 383

Plotting Legend On Pandas Plot

I have the current dataframe:

enter image description here

I have used the pandas inbuilt plot to kind of plot the different regions on 1 graph against each other and got the following result:

plotting_df = df_grouped[[*type_list]]
plotting_df = plotting_df.reset_index()
plotting_df.plot(x='year', y='all_motor_vehicles', kind = 'scatter', legend = True)

enter image description here

I just wanted to know how I could make it so the things that are plotted are labelled with the legends they correspond to in region_name and was wondering how I could get it as a continuous line as using 'line' as the kind just gives me vertical lines. Cheers.

Upvotes: 0

Views: 965

Answers (1)

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

Take region_name A, B, C, D as example

import pandas as pd
import matplotlib.pyplot as plt

iterables = [[2000, 2019], ['A', 'B', 'C', 'D']]

index = pd.MultiIndex.from_product(iterables, names=['year', 'region_name'])

df = pd.DataFrame({'all_motor_vehicles': range(1, 9), 'pedal_cycles': range(1, 9)}, index=index)

unstacked = df.unstack(level=1)

unstacked.plot(y='all_motor_vehicles')

plt.gca().set_xticks(unstacked.index.values)
plt.gca().set_ylabel("all_motor_vehicles")

plt.show()

enter image description here

Upvotes: 2

Related Questions