3

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
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Katharina Böhm
  • 125
  • 1
  • 8

1 Answers1

3

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

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
rpanai
  • 12,515
  • 2
  • 42
  • 64