Creating a bar graph in Python using data from a CSV file is a common and convenient way to visualize data.
This is especially useful when dealing with a large amount of data or when the data changes repeatedly over time. In this tutorial, we will be using Python along with two powerful libraries, Pandas and Matplotlib, to load a CSV file and create a bar graph.
Before we start, make sure you have these libraries installed in your Python environment. If not, you can install them using pip.
Below is an example CSV file we’ll work with in this tutorial. The file contains the scores of two students in three subjects.
Name,Maths,Physics,Chemistry John,85,90,95 Alice,80,85,90
Step 1: Importing the necessary libraries
First off, we will import the necessary libraries which include Pandas and Matplotlib.
1 2 |
import pandas as pd import matplotlib.pyplot as plt |
Step 2: Loading the CSV file
Next, we load the CSV file using the read_csv() function in pandas.
1 |
df = pd.read_csv('scores.csv') |
Step 3: Plotting the bar graph
Finally, we plot the bar graph using the plot function in Matplotlib.
1 2 |
df.plot(x='Name', kind='bar', stacked=False) plt.show() |
The ‘x’ parameter is set to ‘Name’ so that the names are displayed on the x-axis. The ‘kind’ parameter is set to ‘bar’ to specify that we want a bar graph. If ‘stacked’ is set to True, the bars for each student’s scores would be stacked upon one another.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 |
import pandas as pd import matplotlib.pyplot as plt # Load CSV file df = pd.read_csv('scores.csv') # Plotting the bar graph df.plot(x='Name', kind='bar', stacked=False) # To show the plot plt.show() |
The output of the above code will be a bar graph displaying the scores of John and Alice in three different subjects: Maths, Physics, and Chemistry.
Conclusion
In this tutorial, we walked through how to plot a bar graph in Python using a CSV file. The process involves importing the necessary libraries, loading the CSV file, and plotting the graph with specific parameters.
This simple yet powerful technique can be really helpful when you need to visualize large amounts of data in a way that is easily understandable.