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 use the pandas series plot()
function to plot other plots like histograms, bar charts, pie charts, etc. For this, pass the suitable value to the kind
parameter in which ‘line’ is the default value.
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.
1. Quick Examples of Convert Series to Plot
If you are in a hurry below are some quick examples of how to convert the series into a plot.
# Following are the quick examples
# 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)
2. Syntax of Pandas Series.plot()
Following is the syntax of the Series.plot()
.
# Syntax of series.plot
series.plot(*args, **kwargs)
2.1 Parameters of plot() function
Following are the parameters of the plot() function.
data
: Series or DataFrame.x:
label or position, default None. Only used if data is a DataFrame.y:
label, position or list of label, positions, default None. It allows plotting of multiple columns. Only used if data is a DataFrame.kind:
str
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.
2.2 Return Value
It returns matplotlib.axes.Axes
or numpy.ndarray of them
3. Usage of Plot() Function
Python Pandas library is mainly focused on data analysis and it is not only a data visualization library but also using this we can create basic plots. When we want to create exploratory data analysis plots, pandas are highly useful and practical. It provides plot()
and several other wrapper functions for visualizing our data. Let’s use this pandas plot()
function to create a plot for the Pandas series.
4. Create Pandas Series Plot using Matplotlib
Pandas Series is a one-dimensional, Index-labeled data structure that is available only in the Pandas library. It can store all data types such as strings, integer, float, and other python objects. We can access each element in the Series with the help of corresponding default indices.
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.
5. 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
5.1 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.
6. 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, I have explained 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?
- How to Generate Time Series Plot in Pandas
- How to Plot the Boxplot from DataFrame?
- 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
- How to distribute the column values in Pandas plot?
- How to create Pandas histogram plot?
- How to make a histogram in Pandas Series?