Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting with pandas groupby in python, multiple plots

I would like to make three different plots (by location) with data similar to the df I created down below. On the x axis I need the date and the number on the y axis. Preferably, they would be barcharts with a bar for each date. Is it possible to do it in a few simple lines using e.g. the groupby function for the location? Thank you!

data = {"location": ["USA", "USA", "USA", "UK", "UK", "UK", "World", "World", "World"], "date": ["21-06-2021", "22-06-2021", "23-06-2021", "21-06-2021", "22-06-2021", "23-06-2021", "21-06-2021", "22-06-2021", "23-06-2021"], "number": [456, 543, 675, 543, 765, 345, 654, 345, 654]}

import pandas as pd
df = pd.DataFrame (data, columns = ['location','date','number'])
df["date"] = pd.to_datetime(df["date"])
df
like image 380
Katharina Böhm Avatar asked Mar 22 '26 04:03

Katharina Böhm


1 Answers

You are not doing a groupby here, you only want to have a different line for each location.

Sample Data

# using data from OP
df = pd.DataFrame (data, columns = ['location','date','number'])

# using .dt.date will remove the time component for nicer x-axis labels
df["date"] = pd.to_datetime(df["date"]).dt.date

Line Plots

Plotly

import plotly.express as px

px.line(df, x='date', y="number", color="location")

enter image description here

Seaborn

import seaborn as sns

p = sns.catplot(data=df, x='date', y="number", hue='location', kind='point', height=4, aspect=1.5)

enter image description here

Pandas

If you prefer to use pandas only you can follow this answer

  • pandas.DataFrame.plot
pv = df.pivot(index="date", columns='location', values='number')

ax = pv.plot(figsize=(16, 6))

enter image description here

My suggestion here is try to use plotly. You can have nice interactive plots and the syntax is straightforward.

Bar Plots

Plotly

px.bar(df, x='date', y="number", color="location", barmode='group')

enter image description here

Seaborn

p = sns.catplot(data=df, x='date', y="number", hue='location', kind='bar', height=4, aspect=1.5)

enter image description here

Pandas

ax = pv.plot(kind='bar', figsize=(8, 5), rot=0)

enter image description here

like image 146
rpanai Avatar answered Mar 23 '26 18:03

rpanai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!