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:

1 2 |
import pandas as pd import matplotlib.pyplot as plt |

#### 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):

1 |
file_path = 'example.xlsx' |

Now, we will use the `pd.read_excel()`

function to read the Excel file:

1 |
df = pd.read_excel(file_path) |

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:

1 |
print(df.head()) |

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:

1 2 |
x = df['Year'] y = df['Sales'] |

#### 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:

1 |
plt.plot(x, y) |

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

1 2 3 |
plt.title("Sales over years") plt.xlabel("Year") plt.ylabel("Sales") |

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

function:

1 |
plt.show() |

## Full code:

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import pandas as pd import matplotlib.pyplot as plt file_path = 'example.xlsx' df = pd.read_excel(file_path) x = df['Year'] y = df['Sales'] plt.plot(x, y) plt.title("Sales over years") plt.xlabel("Year") plt.ylabel("Sales") plt.show() |

## 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.