Plot Types

Let’s learn about the plot types available in pandas.

There are several built-in plot types in pandas. Most of these are statistical plots by nature. Some examples of built-in plot types are given below:

  • df.plot.area
  • df.plot.bar
  • df.plot.barh
  • df.plot.hist
  • df.plot.line
  • df.plot.scatter
  • df.plot.box
  • df.plot.hexbin
  • df.plot.kde
  • df.plot.density
  • df.plot.pie

We can also, instead of using the methods above, call df.plot(kind='hist') and replace the kind argument with any of the key terms shown in the list above (like 'box', 'barh', and so on).

Let’s go through these plots one by one using our Data Frames df1 and df2.

Press + to interact
# let's do some imports first
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# We can use date_range function from pandas
# periods = 500, no of periods (days) to generate
dates = pd.date_range('1/1/2000', periods=500)
# Setting seed so that we all get the same random number.
np.random.seed(42) # To Do: Try without the seed or use a different number and see the difference!
# Let's generate a series using rand()
col_D = np.random.rand(500)
# Let's use numpy's randn for "standard normal" distribution
data1 = np.random.randn(500,3) #(500,3) to tell the shape we want
# randn(1000,4) 1000 by 4 - 2D array
df1 = pd.DataFrame(data = data1, index=dates, columns=['A', 'B', 'C'])
df1['D']=col_D # recall from pandas data analysis section, how to add a column into your DataFrame!
# rand(20,3) 20 by 3 - 2D array
# Setting seed so that we all get the same random number.
np.random.seed(42) # To Do: Try without the seed or use a different number and see the difference!
data2 = np.random.rand(20,3)
col = ['X', 'Y', 'Z']
df2 = pd.DataFrame(data = data2, columns=col)
print("Dataframes are created..")

Area plot

This is used to plot a stacked area:

Press + to interact
df2.plot.area(alpha=0.5)

Bar plots

We can plot our DataFrame as bars as well:

Press + to interact
df2.plot.bar()

Horizontal bar plots

The barh() method is used to print the DataFrame as a horizontal bar plot. Let’s see this with an example:

Press + to interact
# Horizontal bars
df2.plot.barh()

Stacked bar plot

We can stack them on top of ...