App: Visualization#

Section Title: Visualization

Matplotlib#

Matplotlib, a Python library, supports the creation of various types of visualizations in Python. It is commonly imported as:

import matplotlib.pyplot as plt

Scatterplot#

A scatter plot shows points on a graph using dots. Each dot represents a point’s location, given by its x and y coordinates.

  • These coordinates are like labels for the variables being compared.

  • For example, if we’re comparing a mouse’s weight and height, weight would go on the x-axis and height on the y-axis.

To create a scatetter plot:

  • Use plt.scatterplot()

  • (x_coordinate, y-coordinate) should be given for a single point

  • (x_coordinate sequence, y-coordinate sequence) should be given for multiple points

    • sequence can be a tuple, list, series

  • Using a semicolon prevents the return value from being printed.

    • In plotting, using a semicolon stops the resulting plot object from being printed.

  • For more information on plt.scatterplot() and its parameters, visit the following link.

# single point
plt.scatter(5,10);   # x=5, y=10
_images/cfffa6c0db918cbc70122f45ddc755773e67fa14543f54546b45342017019e06.png
  • In the following code the points are: \((2,10), (4,3), (5,6)\).

# multiple points
plt.scatter((2,4,5),(10,3,6));  
_images/109e8cc6a544bb0b99e8c36aadcbd8f8bf0dbfb166e61d8f5b16bbd4f85c4cd8.png

Color#

The c or color parameter is used to change the colors of the markers.

  • ‘r’ can be used to represent ‘red’

  • ‘g’ can be used to represent ‘green’

  • ‘k’ can be used to represent ‘black’

plt.scatter((2,4,5),(10,3,6), c='red');    
_images/418d82b238ebfc9049e154ec657163f48a6d0ad0c92fefea03a4418f3178d013.png
plt.scatter((2,4,5),(10,3,6), color='r');    
_images/418d82b238ebfc9049e154ec657163f48a6d0ad0c92fefea03a4418f3178d013.png
  • A tuple of colors can be provided to assign each marker a different color.

plt.scatter((2,4,5),(10,3,6), color=('navy','k','r'));
_images/fdb55cae24abc1b86ad20a7c74057b59da8d76e6074e57be84ec9376a5320093.png

Size#

  • The s parameter is used to change the size of the markers.

plt.scatter((2,4,5),(10,3,6), s=300);  
_images/e613136359fa792c10d356db94d9d5510bb42b09c0b2d4814f1aa7e05a19fb67.png
plt.scatter((2,4,5),(10,3,6), s=300, c='r');  
_images/c43b805c6df494381596f4a65f660d24f3ae279493619f9bdcf3a71e26cc9eb9.png
  • A tuple of sizes can be provided to assign each marker a different size.

plt.scatter((2,4,5),(10,3,6), s=(10, 100, 1000));
_images/3bac8d34f4239f4557daa16a00d679d124bc95b7a321dc5bc3c9eaec186dde15.png

Marker#

The marker parameter is used to change the style of the markers. For more marker styles visit the following link.

plt.scatter((2,4,5),(10,3,6), marker='+');
_images/32c23a7384067686e0a84c30bbcddace446e6287b66650138c6374db4bfff145.png
# H: hexagon
plt.scatter((2,4,5),(10,3,6), marker='H', s=200);
_images/cefeffccd43d11ec3070b01218ebe4a09bb08efc0a7b68a5a93eeca126e04555.png

Transparancy#

The alpha parameter, ranging from 0 (transparent) to 1 (opaque), is used to adjust the transparency of the markers.

# H: hexagon
plt.scatter((2,4,5),(10,3,6), alpha=0.2, s=200);
_images/72f7b225a8f16714ab251ddafd01575bdda59ecc6d10d6e59281db2b199694b0.png
plt.scatter((2,4,5),(10,3,6), alpha=(0.1, 0.4, 0.8), s=200);
_images/eaa4c407f1305e6e510fbbd6b6c0701592eb30e667d6505230a0e1fd13297931.png

Chart Elements#

Title#

plt.title() is used to include a title in a figure.

plt.title('Three Red Points')
plt.scatter((2,4,5),(10,3,6), c='r');
_images/a4bef497a78108a1be3519a78dad3321183126d4d31c9136c7542bf6a5eee4b4.png
  • The parameters fontsize, c, family, and loc are used to adjust the properties of the title.

    • c: color

    • loc: location (‘center’, ‘left’, ‘right’)

    • family: font

plt.title('Three Red Points', fontsize=30, c='navy', family='fantasy', loc='left')
plt.scatter((2,4,5),(10,3,6), c='r');
_images/2bfca2085a929360959d448ec6062b0c53edb17489f59ed6acf0ed6528380192.png

Axis Labels#

plt.xlabel() and plt.ylabel() are used to add axis labels to the figure.

plt.xlabel('Weight')
plt.ylabel('Height')
plt.scatter((2,4,5),(10,3,6), c='red');    
_images/85fd7aee9b202a762529ea2dc0a81c110591606f1917323c09b5d3c78dadbb55.png

Axis Ticks#

The tick locations and labels can be modified using plt.xticks() and plt.yticks().

plt.scatter([2,4,5],[10,3,6])
plt.xticks([2,4,5], ['Washington', 'Alabama','Virginia']);
_images/378900e973878f00bf0b3be81f66dc8173dad958d9362b5b99952643bfab1c15.png
# rotation
plt.scatter([2,4,5],[10,3,6])
plt.xticks([2,4,5], ['Washington', 'Alabama','Virginia'], rotation=90);
_images/56ebacfb45bc144584a57855a9770e6712ef3c42d633426974473973f2de2041.png

Remove Axis#

plt.axis(‘off’) is used to remove axis.

plt.scatter((2,3,4,5,6),(1,2,5,2,3), c='red', s=100)
plt.axis('off');    
_images/15dbd6cd243604850bc86e5329354fc32a2729b7f8813c03fc8268cf2d4323a6.png

Grids#

plt.grid() is used to add horizontal and vertical gridlines to the plot.

  • axis parameter is used to achoose the gridline types.

    • Only vertical gridlines: axis = ‘x’.

    • Only horizontal gridlines: axis = ‘y’.

plt.scatter([2,4,5],[10,3,6])
plt.grid()
_images/9034592daf366002dd4bf7b2b7f04b7b389cd64b903c4465a20cbf896a51c1ff.png
plt.scatter([2,4,5],[10,3,6])
plt.grid(axis='x')
_images/d9675d3ba2046e6bcbee507651db4b99c86147a0352d57f1d973fe3a5310ce50.png
plt.scatter([2,4,5],[10,3,6])
plt.grid(axis='y')
_images/fb74c3e6149936d3d646cc32a96333697030345dc1bd21e952d0c734834f015b.png

Text#

plt.text() is used to insert a text into a figure.

  • It is used in the form of plt.text(x, y, text).

  • (x, y) denotes the starting point of the text.

plt.scatter([2,4,5],[10,3,6])
plt.text(4.05,3,'Alabama');   # starts from the point (4.05,3)
_images/94ef21c818a761930fde77041bd3c9badd75af846befc35ad899773f21dd2f46.png

Subplot#

plt.subplot() is used to create multiple plots within a single figure. Before the code for each subplot, plt.subplot() is added with the total number of rows and columns, as well as the order of the subplot. The order of the subplot starts from 1.

  • In the code below the figure has 1 row and 3 columns so in total there are 3 horizontal plots.

    • 1st plot: plt.subplot(1,3,1)

    • 2nd plot: plt.subplot(1,3,2)

    • 3rd plot: plt.subplot(1,3,3)

# number of rows: 1
# number of columns: 3

plt.figure(figsize=(20,5))
plt.subplot(1,3,1)                   # 1st plot
plt.scatter([2,4],[8,7],c='r')
plt.subplot(1,3,2)                   # 2nd plot
plt.scatter([1,2],[5,12],c='b')
plt.subplot(1,3,3)                   # 3rd plot
plt.scatter([6,10],[1,2],c='g');
_images/b1ba65f1896c44621f1ba00f5c3d079f0740b2432e3e97ee6b2bcb1d9443d097.png

Colormap#

You can choose a marker color by using a scalar or sequence of numbers, which will be mapped to colors using cmap. The following link provides access to various colormaps.

The default color map is viridis which ranges between blue and yellow.

  • The largest number, 10, corresponds to yellow.

  • 5 correspons to green.

  • The smallest number, 1, corresponds to (dark) blue

plt.scatter([1,2,3], [3,5,7], c=[1,5,10], s=500);
_images/43835a39d5da221ad44218a69751ed08495cbaaa3535d5400770411149a03f6b.png

cmap parameter is used to change the colormap.For the gray colormap:

  • The largest number, 10, corresponds to white.

  • 5 corresponds to a gray color.

  • The smallest number, 1, corresponds to black

plt.scatter([1,2,3], [3,5,7], c=[1,5,10], s=500, cmap='gray');
_images/0b4dd7370ddb41ca25018c89cdffd47dc1671c4cf53a949ffa03457aeed7a4ea.png

Lineplot#

plt.plot() is used to generate line plots.

  • The x and y coordinates of the points are provided similarly to plt.scatter().

  • The points are connected by line segments.

  • If x coordinates are not specified, plt.plot() uses default x values: 0, 1, 2, and so on.

  • However, for plt.scatter(), x coordinates must be explicitly provided.

The following lineplot connects (1,7) and (3,10).

plt.plot((1,3),(7,10)); 
_images/24a5d327f6d3f26ce187f9d534174d1296f95b8cfe57d85d861347652b883730.png

The following lineplot connects (1,7), (2,5) and (3,10).

plt.plot((1,2,3),(7,5,10)); 
_images/3b587d4ddea1c1710980957d4cd720cd820ee663e2b4af61f4a2fc2fae6a757b.png

Marker#

The marker parameter is used to specify the style of the markers.

plt.plot((1,2,3),(7,5,10), marker='o'); 
_images/91defa13ebdb8bdb5a97fa634c351650080d32c5fbe62daee267c716f8e26a73.png

Markersize#

The markersize parameter is used to adjust the size of the marker.

plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), marker='*', markersize='20'); 
_images/c937bd6504e537353b1f56292ac81fafb4877e475ecda84a19e61b8d388ed5a2.png

Linewidth#

The linewidth parameter is used to adjust the thickness of the line segments.

plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), linewidth=5); 
_images/c187161d67c2d857410cd4cd08509f0f145573c97cf2913c9b8b4dab5037771c.png

Linestyle#

The linestyle parameter is used to adjust the style of the line segments.

  • Choices: ‘-’, ‘–’, ‘-.’, ‘:’, ‘None’, ‘ ‘, ‘’, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’

plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), linestyle='dashed'); 
_images/fed390a2defe1a85d4e6cb8bc822488dd98f4ccc62c510cc79b23d391337dfa3.png
plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), linestyle='dotted'); 
_images/77f5b4c8d6551b5d0c556bd999e552c8b9d64dba654a601b0f35c6455e7ec433.png
plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), linestyle='dashdot'); 
_images/538b4dc8d587721d2e8ec9f5cd969e774f5775ed04b6b5c39b11cec004c8d65b.png

Color#

The c or color parameter is used to adjust the color of the line segments and markers.

plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), c='r'); 
_images/90732b0e875d7cfb1e2cf9c537deaf6a4bbbc28c42f6bc98e458f1311b909e42.png
plt.plot((1,2,3,4,5,6),(7,5,10,2,7,1), marker='*', color='r'); 
_images/81935ca37c022127ad686ea37bf2f99e30839b3ffecbac2b1a67707aa466f32d.png

Barplot#

plt.bar() is used to generate bar plots.

  • A bar plot represents values corresponding to categories as vertical bars.

  • The categories and their values are specified by the first and second arguments of the plt.bar() function, respectively.

In the following code, categories are represented by the expenses tuple, and the corresponding values are represented by the cost tuple.

  • The color parameter is used to change the colors of the bars.

expenses = ('housing', 'tuition', 'transportation', 'supplies', 'food')
cost = (700, 1000, 200, 100, 500)
color_set = ('y', 'r', 'g', 'orange', 'navy')

plt.bar(expenses, cost, color=color_set);
_images/903467086ed61886d0d18e56f7f731437a5ac4254b0db9995086d0107cc8e8e8.png

Functions#

You can plot a function by generating x coordinates using np.linspace() and calculating corresponding y coordinates using functions from the numpy module.

  • np.linspace(start, stop, num) returns num evenly spaced numbers between start and end.

Square#

The following code generates 10 evenly spaced numbers between -1 and 1 and calculates their square values.

import numpy as np

x = np.linspace(-1, 1, 5) 
y = x**2

plt.plot(x,y);
_images/c4068514f909906f4882e23bf74a679ce9afcef3eb8472d8008c46962dc46b67.png

In the graph above, we can recognize the individual line segments. Now, let’s increase the number of points.

import numpy as np

x = np.linspace(-1, 1, 100) 
y = x**2

plt.plot(x,y);
_images/434d86d9c782854b250288a1754e56dc9b3bbc516af595e89a6436620a29cf09.png
  • The graph appears as a curve, although it’s actually composed of line segments.

  • However, these segments are small, so when combined, they resemble a curve.

  • As evident from the plot below, the line segments are quite small.

import numpy as np

x = np.linspace(-1, 1, 100) 
y = x**2

plt.plot(x,y, marker='o');
_images/03c77f5c7cee3e6ded78ef20543e9d4d657e5643d4eef9866f6a9de2dba0e243.png

sin(x)#

The following code generates 100 evenly spaced numbers between 0 and 10 and calculates their corresponding sine values.

import math
import numpy as np

x = np.linspace(0, 30, 100) 
y = np.sin(x)

plt.plot(x,y);
_images/75718f41e08e7ca6ec26d8185c3593f4877bb6d5d460e7fe7d6424710ff5b37f.png

Polynomials#

The following code generates 100 evenly spaced numbers between -4 and 5 and calculates their corresponding polynomial values.

  • The polynomial is \(x^3-2x^2-3x\)

import numpy as np

x = np.linspace(-4, 5, 100) 
y = x**3-2*x**2-3*x

plt.plot(x,y);
_images/9db3b5046d08067dfa54f546f6cb7543ce8a533b78553bf0fb1df08a302089b3.png

Squareroot#

import numpy as np

x = np.linspace(0, 10, 100) 
y = np.sqrt(x)

plt.plot(x,y);
_images/7e31b379e44f7779a6ffa2a10902d37baf70f1a701185222255cfe4782141e3c.png

Exponential#

import numpy as np

x = np.linspace(-2, 10, 100) 
y = np.exp(x)

plt.plot(x,y);
_images/5cafa46f91a3f7be275deeca10e0dfc2250ac5a1a16c9dae1fc31eb6480738ab.png