Pandas is a Python library widely used in the Data Science field for data analysis and manipulation. You can analyze your data in visual form using the Python libraries to plot your data in the form of plots or graphs/charts. Let’s dive into the article to find out how to create plots using Pandas.
Create a dataframe
Let’s create a data frame first using the Pandas library.
import pandas as pd df = pd.read_csv("example.csv") print(df)
Here, in the code, you first import the Pandas library using the import statement. Next, you read a CSV file and create a data frame having the contents of that CSV file. We apply the head() method on the data frame to view the top three rows in the data frame.
This is how the output of the code will look like.
Also read: How to plot multiple lines in Matlab?
Plot the dataframe
The Pandas library provides you with the methods to manipulate the data. It also provides you with the method to create plots to visualize your data. Additionally, there are some Python libraries such as Seaborn or Matplotlib using which you can plot your data into the form of charts or graphs or plots. Let’s go through them to understand how to create a plot.
Plot using the plot() method of the Pandas library
You can use the plot() method of the Pandas library on the data frame to plot bar plots or scatter plots, or histograms. Specify the column name of X and Y and the type of plot you want as the parameters of the plot() method.
df.plot(x="Name", y="Science", kind="bar") df.plot(x="Name", y="English", kind="scatter")
The following screenshot shows how your output will look like a bar graph.
The following screenshot shows how your output will look like a scatter graph.
Plot using the matplotlib library
You can use the matplotlib library to plot charts or graphs. Import the pyplot submodule under the matplotlib module. To create a pie chart, you can use the pie() method shown in the code below. Use the show() method to display the chart in your output.
import matplotlib.pyplot as plt plt.pie(df["Maths"],labels = df["Name"]) plt.show()
The output of the above code is given below.
Plotting using the seaborn library
You can use the Seaborn library to plot the graph or charts. See the example code given below.
import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid") ax = sns.stripplot(x=df['Name'], y=df['Maths']) plt.title('Graph using Seaborn') plt.show()
You can set your graph’s background style using the set() method. Use the stripplot() method to plot the graph and specify the X and Y values for the graph as the method’s parameters. You can set your graph’s title by the title() method. See the image below to see how the output will look.
You can try to create various graphs on your own using the libraries such as matplotlib, seaborn, plotly, and Pandas.
Also read: How to fix Dev C++ build error?
An avid reader and an engineering student. Love to code and read books. Always curious to learn new things 🙂