How To Plot Graph In Python Using Excel File

In this tutorial, we will learn how to plot a graph in Python using an Excel file. We will use the widely-used Python libraries, pandas and matplotlib, to visualize the data extracted from the Excel file.

Step 1: Import the required libraries

In order to work with Excel files and plot graphs, we need to import the necessary libraries. We will use pandas to read the Excel file and matplotlib to plot the data. Let’s import both libraries:

Step 2: Load the Excel file

We will now load our Excel file using the Pandas library. First, we need to specify the file path (replace the 'your_file_path_here.xlsx' with your Excel file path):

Now, we will use the pd.read_excel() function to read the Excel file:

Here, df is a DataFrame object which will store the data from the Excel file.

Example Excel file content:

Year    Sales
2017    25000
2018    28000
2019    30000
2020    32000
2021    35000
2022	39000

Step 3: Explore and prepare the data

Before plotting the graph, it is important to explore and understand the data. We can use the pandas head() function to display the first five rows of the DataFrame:

Now, let’s define the x-axis and y-axis data for our graph. For this tutorial, we will use the ‘Year’ column for the x-axis and the ‘Sales’ column for the y-axis:

Step 4: Plot the graph using matplotlib

Now, we will use the matplotlib library to plot the graph. We will create a line plot using the plt.plot() function and provide the x and y-axis data:

Next, we will add title and labels for our graph:

Finally, we will display the graph using the plt.show() function:

Full code:

Here’s the full code to plot a graph in Python using an Excel file:

Output

Conclusion

In this tutorial, we have learned how to plot a graph in Python using an Excel file. By using the pandas and matplotlib libraries, we were able to load data from an Excel file, prepare the data for plotting, and visualize the data using different types of graphs. This skill is essential for data analysis and visualization in various fields.