Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Data Visualization with Python

Using Python libraries Matplotlib and seaborn to apply some popular data visualization techniques.

5 min readMar 9, 2022

--

Press enter or click to view image in full size
credits: jovian.ai

Data visualization is an essential part of data analysis. Here we will use Python libraries Matplotlib and seaborn to apply some popular data visualization techniques.

Importing Libraries

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline # to make sure our plots display in same window

Line Chart

plot function on default draws a lineplot.

Basic plot

plt.plot(y_axisdata)#plots against count on x-axis(for each datapoint) on defaulty_axisdata=[0.5,0.4,0.7,0.99,0.1]
X_axisdata=[1999,2000,2001]
plt.plot(xaxisdata,y_axisdata);#semicolon at end helps to display only the plot without returning the plot list that are drawn

Multiple plots within the same graph with a marker to differentiate data points.

plt.plot( x_axisdata1,y_axisdata, marker='o')
plt.plot( x_axisdata2,y_axisdata, marker='x')

Adding labels

plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')

plt.title("Graph title")
plt.legend(['graphline1 name', 'graphline2 name'])#incase of multiple plots within same graph

Styling graph plots

color or c: Set the color of the line (supported colors)

linestyle or ls: Choose between a solid or dashed line

linewidth or lw: Set the width of a line

markersize or ms: Set the size of markers

markeredgecolor or mec: Set the edge color for markers

markeredgewidth or mew: Set the edge width for markers

markerfacecolor or mfc: Set the fill color for markers

alpha: Opacity of the plot

plt.plot(x_axisdata, y_axisdata, marker='s', c='b', ls='-', lw=2, ms=8, mew=2, mec='navy')
plt.plot(x_axisdata, y_axisdata, marker='o', c='r', ls='--', lw=3, ms=10, alpha=.5)

Multiple styles in one argument:

plt.plot(x_axisdata, y_axisdata,'s--b')#marker shape, line style, and line color.
plt.plot(x_axisdata, y_axisdata,'sb')#considers only marker shape and line color.

Changing figure size:

plt.figure(figsize=(12, 6))

Using sample seaborn styles:

sns.set_style("whitegrid")
sns.set_style("darkgrid")

Changing default matplotlib styles.

Use rcparams:

matplotlib.rcParams['font.size'] = 16
matplotlib.rcParams['figure.figsize'] = (7, 4)
matplotlib.rcParams['figure.facecolor'] = '#00000000'

Scatter Plot

sns.scatterplot(x=dataset_df.col1, y=dataset_df.col2, hue=dataset_df.col3, s=100);

Hues are the third feature that helps to distinguish all the data points of a dataset, it gives us insights between different categories(in different colors) in the dataset, s is the size of a datapoint.

Plotting using a dataframe:

# Load data into a Pandas dataframe
dataset_df = sns.load_dataset("dataset_name")
sns.scatterplot(x='col1',
y='col2',
hue='col3',
s=100,
data=dataset_df);

Histogram

This helps us to identify the interval/range of our data points in from of bins:

plt.hist(dataset_df.colname);

Controlling the bin range:

plt.hist(dataset_df.colname,bins=np.arange(2, 5, 0.25));
plt.hist(dataset_df.colname,bins=5);
plt.hist(dataset_df.colname,bins=[1, 3, 4, 4.5])

Multiple plots:

By changing the opacity we can have the plots one on another.

plt.hist(dataset_df.col2, alpha=0.4, bins=np.arange(2, 5, 0.25));
plt.hist(dataset_df.col1, alpha=0.4, bins=np.arange(2, 5, 0.25));

Stack multiple histograms one on another.

plt.hist([dataset_df.col1, dataset_df.col2,dataset_df.col3], 
bins=np.arange(2, 5, 0.25),
stacked=True);

Bar chart

Similar to line chart where instead of the line we will see a bar for each data point.

Similar to histograms we can stack bars one on another using the “bottom” argument.

plt.bar(x_axisdata, y_axisdata1, bottom=y_axisdata2);

Plotting dataset for barchart in the same way of scatter plot.

Get Jayashree Mallipudi’s stories in your inbox

Join Medium for free to get updates from this writer.

it needs x, y, hue, size(s), and dataset as parameters.

Heatmap

A heatmap is used to visualize 2-dimensional data like a matrix or a table using colors.

For example dataset_df contains year(columns), month(rows), sales(values in matrix for each month in each year).

In this scenario, heatmap represents a year on the x-axis and a month on the y-axis and data represents sales with different shades of colors from dark to bright.

Brighter shades represent the higher sales with respect to year and month.

sns.heatmap(dataset_df, fmt="d", annot=True, cmap='Blues');
#annot=true helps to show actual values in each block
#cmap argument to change the color palette

Contour Plot

It uses color-coded regions to visualize 3 variables (x-axis, y-axis, value point (described by color gradient) in two dimensions.

sns.kdeplot(dataset_df.col1, dataset_df.col2, shade=True, cmap='Reds', shade_lowest=False)

Box Plot

Distribution of data along single axes

sns.boxplot(dataset_df.col1, dataset_df.col2, hue=dataset_df.categorycolname);

Images

We can use Matplotlib to display images.

Downloading image from URL into a file.

from urllib.request import urlretrieve
urlretrieve('https://image_url.jpg', 'filenametobesaved.jpg');

Read Image into memory first using PIL module.

Image is loaded into a 3D array with (RGB)pixel intensities.

from PIL import Image
img = Image.open('filenametobesaved.jpg')
img_array = np.array(img)
plt.imshow(img);

The image will be displayed inside an array so in order to remove them and to display only the image we need to turn off the grid, axes:

plt.grid(False)
plt.axis('off')
plt.imshow(img);

Displaying a part of the image using a slice of NumPy array:

plt.imshow(img_array[125:325,105:305]);

Multiple Charts in a grid

We need multiple axes for multiple plots in the same grid. We use a subplot for this purpose which returns multiple axes.

#Here we divide grid into 2 rows and 3 columns each can have a plot of figure size(16,8)->total 6 plots
fig, axes = plt.subplots(2, 3, figsize=(16, 8))

Axes subplot can be accessed in form of:

axes[0,0]->1st row and 1st col axes
axes[0,0].plot(x_axisdata, y_axisdata,'s--b')

In the same way we can use axes to assign label,styles,title,legend,Instead of plt.function() we use as axes[row,col].function() since axes is a part of plot.

Plotting by passing axes

Another way of plotting is by passing axes as parameters.

sns.scatterplot(x=dataset_df.col1, 
y=dataset_df.col2,
hue=dataset_df.col3,
s=100,
ax=axes[0,1]);

Pair Plots

Within the dataframe, if you want to have a plot between every two pairs of features we could use pair plot.

sns.pairplot(dataset_df, hue='col_name(category with which you want to compare pair of features)');

Getting code together

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
#common for any plot
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title("Graph title")
plt.legend(['graphline1 name', 'graphline2 name'])
#line plot
plt.plot(x_axisdata, y_axisdata,'s--b')
#Scatter plot
dataset_df = sns.load_dataset("dataset_name")
sns.scatterplot(x='col1', y='col2', hue='col3',s=100, data=dataset_df)
#Histogram
plt.hist(dataset_df.col1, alpha=0.4, bins=np.arange(2, 5, 0.25))
#stacked histogram
plt.hist([dataset_df.col1, dataset_df.col2,dataset_df.col3],
bins=np.arange(2, 5, 0.25),
stacked=True);
#Bar chart
plt.bar(x_axisdata, y_axisdata1, bottom=y_axisdata2);
#Heatmap
sns.heatmap(dataset_df, fmt="d", annot=True, cmap='Blues');
#Contour plot
sns.kdeplot(dataset_df.col1, dataset_df.col2, shade=True, cmap='Reds', shade_lowest=False)
#box plot
sns.boxplot(dataset_df.col1, dataset_df.col2, hue=dataset_df.categorycolname);
#images
from PIL import Image
img = Image.open('filenametobesaved.jpg')
img_array = np.array(img)
plt.imshow(img)
#multiple plots using subplots
fig, axes = plt.subplots(2, 3, figsize=(16, 8))
axes[0,0].plot(x_axisdata, y_axisdata,'s--b')
(or)
sns.scatterplot(x=dataset_df.col1,
y=dataset_df.col2,
hue=dataset_df.col3,
s=100,
ax=axes[0,1]);
#Pair Plots
sns.pairplot(dataset_df, hue='col_name(category with which you want to compare pair of features)')

Conclusion

This article provides the introduction to different types of data visualization techniques with help of code samples.

Hope you find this helpful.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.