0

I have an Excel file that looks like this:

I would like to plot all 3 individuals' weight on Jan 1, 2020 on a bar chart to compare visually in Python using Matplotlib. How can I do this?

2 Answers 2

1

It's probably easiest done with pandas:

import pandas as pd
import datetime as dt


df = pd.read_excel('your_file_location', sheet_name='sheet_name', parse_dates=['Date'])
df = df.loc[df['Date'] == dt.date(year=2020, month=1, day=1)]
ax = df.plot.bar(df['Name'], df['Weight'])

Here we first load data from a specific sheet of your excel file (you can omit sheet_name argument if your excel file has only a single sheet), then we filter data to show only records from a specific date and then plot with names on x-axis and weight on y-axis.

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

1 Comment

Thank you, I'm still experimenting with it. Would you know how I can plot just two people (ex: Tom Berry and Peter James)?
0
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('C:\\Desktop\\file.csv', index_col = 'Date', 
parse_dates = True)  #importing data to python and making date column as 
index
df['year'] = df.index.year #extracting year from index
data_20 = df[df['year'] == 2020] # Filtering out 2020 date
ax = data_20.plot(kind='bar',x='Name',y='Weight') #Plotting by name for 2020

To plot only for 2 people:

ax = data_20[data_20['Name'] != 'John Smith']
.plot(kind='bar',x='Name',y='Weight') #Plotting by name for 2020
ax.set_ylabel('Weights in lbs') #Labeling y-axis
ax.set_xlabel('Names') #Labeling x-axis
ax.set_title('Weights for 2020') # Adding the title

To make it pretty just add labels:

ax.set_ylabel('Weights in lbs') #Labeling y-axis
ax.set_xlabel('Names') #Labeling x-axis
ax.set_title('Weights for 2020'); # Adding the title

4 Comments

Thank you, I'm still experimenting with it. Would you know how I can plot just two people (ex: Tom Berry and Peter James)?
You can filter out the same way: Just use data_20[data_20['Name'] != 'John Smith'].
Thank you, that works but what if I have say 5 names in Excel and I want to plot only 2 names? I used the following code: data_20 = data_20[data_20['Name']== ['John Smith', 'Peter James']] but it is giving my a "Lengths must match to compare" error. Thank you
data_20[(data_20['Name'] == 'John Smith') | (data_20['Name'] == 'Peter James')].plot(kind='bar',x='Name',y='Weight')

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.