Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

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'sMatplotlib 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 thatMatplotlib library is installed. Following is the command for installing the Matplotlib library −

pip install pandas matplotlib

Importing Libraries

Along with theimport 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 likeJupyter Notebook orIPython shell, plots are often displayed automatically as they are generated. However, in a standardPython script orshell, 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 calledplot() on both the Series and DataFrame objects for plotting different kind plots. This method is a simple wrapper around thematplotlibplt.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 Pandasplot() method.

import pandas as pdimport numpy as npimport 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 DataFramedf.plot()plt.show()

Itsoutput is as follows −

Basic Plotting

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

Also we can plot one column versus another using thex andy keywords.

Types of Plots Available in Pandas

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

Plot Typekind ValueSpecialized MethodUse 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 −

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

Itsoutput is as follows −

Bar Plot

To produce a stacked bar plot,pass stacked=True

import pandas as pdimport numpy as npimport 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 plotdf.plot(kind='bar', stacked=True)plt.show()

Itsoutput is as follows −

Stacked Bar Plot

To get horizontal bar plots, use thebarh option −

import pandas as pdimport numpy as npimport 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 plotdf.plot(kind='barh', stacked=True)plt.show()

Itsoutput is as follows −

Horizontal Bar Plot

Histograms

Histograms can be plotted using thehist option of theplot() method kind argument. We can specify number of bins.

import pandas as pdimport numpy as npimport 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()

Itsoutput 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).

import pandas as pdimport numpy as npimport 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()

Itsoutput is as follows −

Box Plots

Area Plot

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

import pandas as pdimport numpy as npimport 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()

Itsoutput is as follows −

Area Plot

Scatter Plot

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

import pandas as pdimport numpy as npimport 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()

Itsoutput is as follows −

Scatter Plot

Pie Chart

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

import pandas as pdimport numpy as npimport 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()

Itsoutput is as follows −

Pie Chart
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp