简体   繁体   English

如何从 Matplotlib 文件中的 Excel 文件中 Plot 特定行?

[英]How Can I Plot Specific Rows from Excel File in Matplotlib?

I have an Excel file that looks like this:我有一个看起来像这样的 Excel 文件:

I would like to plot all 3 individuals' weight on Jan 1, 2020 on a bar chart to compare visually in Python using Matplotlib.我想 plot 在条形图上显示所有 3 个人在 2020 年 1 月 1 日的体重,以便使用 Matplotlib 在 Python 中进行视觉比较。 How can I do this?我怎样才能做到这一点?

It's probably easiest done with pandas:使用 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.在这里,我们首先从 excel 文件的特定工作表中加载数据(如果 excel 文件只有一个工作表,则可以省略sheet_name参数),然后我们过滤数据以仅显示来自特定日期的记录,然后显示名称为 x--44EAA496 的 Z32FA6E1B78A9D402495轴和重量在 y 轴上。

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:至 plot 仅限 2 人:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM