Pandas Series.plot()
function is used to make plots of given series. Python provides various functions to convert our data into a presentable form like never before through its Pandas plot()
function. The default plot of the Pandas Series is a line plot. The pandas series plot()
function returns a matplotlib axes object to which you can add additional formatting.
Note: You can utilize the plot()
function of Pandas Series to generate various types of plots such as histograms, bar charts, pie charts, and more. To do so, simply provide an appropriate value to the kind
parameter. By default, the kind
parameter is set to ‘line’.
In this article, I will explain the plot()
function and using this how we can plot a Series in different visualization of DataFrame.
Key Points –
- Ensure that you have both Pandas and Matplotlib libraries imported in your Python environment to utilize their plotting functionalities.
- Pandas Series objects come with built-in plotting methods. Familiarize yourself with these methods such as
plot()
, which is a wrapper around Matplotlib’s plotting functions. - Before plotting, thoroughly explore and understand the characteristics of the Pandas Series data. Identify patterns, trends, and potential outliers to inform the choice of an appropriate plot type.
- Tailor the plot to the intended audience. Choose visualizations that effectively convey the key insights to your target audience, whether they are technical experts, stakeholders, or the general public.
- Adjust visual elements such as color, markers, and line styles to enhance readability and convey specific information. Use labels and legends to provide context.
Quick Examples of Convert Series to Plot
Following are quick examples of converting the series into a plot.
# Quick examples of convert series to plot
# Example 1: Create Pandas Series plot
# Create Series
s = pd.Series([np.random.randint(1,500) for i in range(1,100)])
p = plt.plot(s.index, s.values)
# Example 2: create timeseries plot
# Create Series
ser = pd.Series({1720: 1483799, 1820: 1660099, 1920: 2045638, 2020: 3221898},
name='population')
ser.plot(x="year", y="people")
plt.xlabel("year", size = 20)
plt.ylabel("people", size = 20)
plt.title("Population", size = 25)
# Example 3: Draw a plot bar chart
ser.plot.bar()
# Set the Bar Plot Labels and Title
ser.plot(x="year", y="people")
plt.xlabel("year", size = 20)
plt.ylabel("people", size = 20)
plt.title("Population", size = 25)
Pandas Series.plot() Introduction
Following is the syntax of the Series.plot()
.
# Syntax of series.plot
series.plot(*args, **kwargs)
Parameters
Following are the parameters of the plot() method.
data
– A Pandas Series or DataFrame.x
– Label or position, with a default value of None. This parameter is only applicable when the data is a DataFrame.y
– label, position, or a list of labels and positions, by default None. This parameter facilitates the plotting of multiple columns and is applicable only when the data is a DataFramekind
– Specifies the type of plot to be created (‘line’, ‘bar’, ‘barh’, ‘hist’, ‘box’, ‘kde’, ‘density’, ‘area’, ‘pie’, ‘scatter’, ‘hexbin’, etc.).
The kind of plot to produce:
line -
line plot (default)bar -
vertical bar plotbarh -
horizontal bar plothist -
histogrambox -
boxplotkde -
Kernel Density Estimation plotdensity -
same as ‘kde’area -
area plotpie -
pie plotscatter -
scatter plot (DataFrame only)hexbin -
hexbin plot (DataFrame only)
**kwargs:
Options to pass to matplotlib plotting method.
Return Value
It returns matplotlib.axes.Axes
or numpy.ndarray of them
Usage of Plot() Function
The Python Pandas library primarily focused data analysis, offering not only robust data visualization capabilities but also the ability to generate fundamental plots. Particularly valuable for exploratory data analysis, Pandas equips users with its plot()
function and a range of other wrapper functions tailored for visualizing data. Let’s use this Pandas plot()
function to create a plot for the Pandas series.
Create Pandas Series Plot using Matplotlib
A Pandas Series represents one-dimensional data indexed with labels, exclusive to the Pandas library. It accommodates diverse data types like strings, integers, floats, and other Python objects. Each element in the Series can be accessed using its respective default index.
Now, let’s create a Pandas series. Here I will create a Series using numpy. random.randint() function.
# Create Series
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s = pd.Series([np.random.randint(1,500) for i in range(1,100)])
print(s)
# Create Pandas Series plot
p = plt.plot(s.index, s.values)
Yields below output.
# Output:
0 487
1 406
2 484
3 76
4 114
94 19
95 58
96 239
97 231
98 10
Length: 99, dtype: int64
Use Pandas Series for plotting where its indices are on the x-axis and values are on the y-axis. This process will be done by using matplotlib.pyplot plot()
method.
Create Series Plot using plot()
Here, I have created a Series using general data based on population and I will use Series.plot()
function to plot the values in a chart.
# Create Series
ser = pd.Series({1720: 1483799, 1820: 1660099, 1920: 2045638, 2020: 3221898},
name='population')
print(ser)
Print(type(ser))
ser.plot()
Yields below output.
# Output:
1720 1483799
1820 1660099
1920 2045638
2020 3221898
Name: population, dtype: int64
Customize the Series plot
We can customize the Series plots by providing any keyword argument. Here, I will customize the timeseries plot by providing axis labels and title using matplotlib.pyplot
.
import matplotlib.pyplot as plt
# Set the timeseries Plot Labels and Title
ser.plot(x="year", y="people")
plt.xlabel("year", size = 20)
plt.ylabel("people", size = 20)
plt.title("Population", size = 25)
Yield below output.
Plot Bar of Series
We can create a bar graph by calling a plot.bar()
on the pandas Series, so let’s create a Series. Here I have created a Series using general data on the population. I have taken a year
as an index
, which is set on an x-axis
label and people
as a measured value, which is set on a y-axis
label.
# Draw a plot bar chart
ser.plot.bar()
# Set the Bar Plot Labels and Title
ser.plot(x="year", y="people")
plt.xlabel("year", size = 20)
plt.ylabel("people", size = 20)
plt.title("Population", size = 25)
Yields below output.
Frequently Asked Questions on Plot the Pandas Series
To plot Pandas Series, you need to import Pandas and Matplotlib libraries. The pd
alias is commonly used for the Pandas library, and plt
is a common alias for the Matplotlib’s pyplot
module. With these imports, you’ll have access to the Pandas DataFrame and Matplotlib’s plotting functionalities, allowing you to create and customize plots for your Pandas Series.
You can customize the plot by providing various parameters to the plot()
method. For example, you can set titles, labels, colors, and more. Refer to the documentation for the full list of customization options.
Common plot types include line plots (kind='line'
), bar plots (kind='bar'
), scatter plots (kind='scatter'
), histograms (kind='hist'
), and many others. The choice depends on the nature of your data and the insights you want to convey.
Check the documentation for the specific plot type you are using, ensure your data is correctly formatted, and review the parameters you are passing to the plot()
method. If issues persist, consider seeking help from online forums or communities.
You can plot multiple Series on the same axes by calling the plot()
method on each Series consecutively before calling plt.show()
. Additionally, you can use the ax
parameter to specify the axes on which to plot.
Seaborn is a statistical data visualization library based on Matplotlib and can be used in conjunction with Pandas for more aesthetically pleasing visualizations. You can explore Seaborn for additional styling options.
Conclusion
In this article, you have learned the Series.plot()
function and using this function how we can plot the different plots in Pandas Series. As well as I explained how to customize the plots by using any keyword argument of plot()
function.
Related Articles
- How to create Pandas Series in Python
- Pandas Window Functions Explained
- How to Create Scatter Plot in Pandas?
- Pandas Handle Missing Data in Dataframe
- How to Change Pandas Plot Size?
- How to add title to Pandas plots?
- How to generate line plot in Pandas?
- How to add legends to plots in Pandas
- Distribute the column values in Pandas plot?
- How to create Pandas histogram plot?