Python Pandas - Visualization



Visualization of data plays an important role in data analysis, it helps you represent the data graphically for better understanding, and identifying the patterns. However, Pandas library is primarily used for data manipulation and analysis but it also provides the data visualization capabilities by using the Python's Matplotlib library support.

In Python, the Pandas library provides a basic method called .plot() for generating a wide variety of visualizations along the different specialized plotting methods. These visualizations tools are built on top of the Python's Matplotlib library, offering flexibility and customization options.

Behind the scenes, every plot generated by Pandas is actually a Matplotlib object. This integration allows users to leverage Matplotlib's extensive customization options for fine-tuning Pandas-generated plots.

In this tutorial, we will learn about basics of visualizing data using the Pandas data structures.

Setting Up the Environment for Visualization

Before learning about Pandas data Visualization, we should ensure that Matplotlib library is installed. Following is the command for installing the Matplotlib library −

pip install pandas matplotlib

Importing Libraries

Along with the import pandas as pd you need to import the Matplotlib's functional interface for displaying, customizing, and saving plots using the following command −

import matplotlib.pyplot as plt

Displaying the plots

In environments like Jupyter Notebook or IPython shell, plots are often displayed automatically as they are generated. However, in a standard Python script or shell, this does not happen automatically. To explicitly display a plot in such environments, we need to call the following command −

plt.show()

This command renders the Matplotlib figure object in a GUI window.

Pandas Basic Plotting Method

The Pandas library provides a basic plotting method called plot() on both the Series and DataFrame objects for plotting different kind plots. This method is a simple wrapper around the matplotlib plt.plot() method.

Syntax

Following is the syntax of the Pandas .plot() method −

DataFrame.plot(*args, **kwargs)

Where,

  • kind: Specifies the type of plot (default: 'line').

  • *args:

  • **kwargs:

Example

Here is the following example of plotting a random DataFrame data using the Pandas plot() method.

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('1/1/2000', periods=10), columns=list('ABCD')) # Plotting the DataFrame df.plot() plt.show()

Its output is as follows −

Basic Plotting

If the index consists of dates, then the pandas .plot() method calls the Matplotlib gct().autofmt_xdate() to format the x-axis labels.

Also we can plot one column versus another using the x and y keywords.

Types of Plots Available in Pandas

Pandas supports various plot types through the kind parameter or specialized plotting methods. Following is the overview of the different plotting methods −

Plot Type kind Value Specialized Method Use Case
Line 'line' .line() Visualizing trends over time or a sequence.
Bar 'bar' .bar() Comparing quantities across categories.
Horizontal Bar 'barh' .barh() Same as bar charts, but horizontal.
Histogram 'hist' .hist() Visualizing Distribution of numeric data.
Box Plot 'box' .box() Summarizing data distribution and outliers.
Area 'area' .area() Highlighting trends with cumulative data.
Scatter 'scatter' .scatter() Relationship between two variables, for DataFrame only.
Hexbin 'hexbin' .hexbin() Visualizing data density in two dimensions, for DataFrame only.
Density 'kde' or 'density' .kde() or .density() Smoothing data distributions (Kernel Density Estimation).
Pie 'pie' .pie() Proportional data in a circular graph.

Example: Plotting Bar Plot with plot() method

Let us now see what a Bar Plot is by creating one. A bar plot can be created in the following way −

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(10,4), columns=['a','b','c','d']) # Plotting the bar plot df.plot(kind='bar') plt.show()

Its output is as follows −

Bar Plot

To produce a stacked bar plot, pass stacked=True

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(10,4), columns=['a','b','c','d']) # Plotting the stacked Bar plot df.plot(kind='bar', stacked=True) plt.show()

Its output is as follows −

Stacked Bar Plot

To get horizontal bar plots, use the barh option −

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(10,4), columns=['a','b','c','d']) # Plotting the horizontal bar plot df.plot(kind='barh', stacked=True) plt.show()

Its output is as follows −

Horizontal Bar Plot

Histograms

Histograms can be plotted using the hist option of the plot() method kind argument. We can specify number of bins.

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame({'a':np.random.randn(1000)+1,'b':np.random.randn(1000), 'c':np.random.randn(1000) - 1}, columns=['a', 'b', 'c']) df.plot(kind='hist', bins=20) plt.show()

Its output is as follows −

Histograms using plot.hist()

Box Plots

Box plot can be drawn calling 'box' option for both the Series and DataFrame objects to visualize the distribution of values within each column.

For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1).

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E']) df.plot(kind='box') plt.show()

Its output is as follows −

Box Plots

Area Plot

Area plot can be created using the plot(kind='area') option.

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) df.plot(kind='area') plt.show()

Its output is as follows −

Area Plot

Scatter Plot

Scatter plot can be created using the plot(kind='scatter') option.

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd']) df.plot(kind='scatter', x='a', y='b') plt.show()

Its output is as follows −

Scatter Plot

Pie Chart

Pie chart can be created using the plot(kind='pie') option.

Open Compiler
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Creating a random DataFrame df = pd.DataFrame(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], columns=['x']) df.plot(kind='pie', subplots=True) plt.show()

Its output is as follows −

Pie Chart
Advertisements