<jupyter_start><jupyter_text>Plotting and Visualization Using `Matplotlib`- Making plots is one of the most critical tasks in data science- `Matplotlib` is a desktop package for creating primarily 2D publication-ready plots - Inspired by MATLAB and commands almost equivalent across MATLAB and Matplotlib- `Matplotlib` has spawned many add-on toolkits for data visualization that build on top of `Matplotlib`  Some Popular Plotting Tools* Seaborn: https://seaborn.pydata.org/examples/index.html  * Desktop publishing with best practices to that is based on research on how people best perceive information  * Excellent default parameters* Plotly (https://plot.ly/python/)  * Has an API for Python (as well as other languages)  * The app itself is built on Python and DJANGO  * The same company that created Dash      Some Popular Plotting Tools - Cont'd* Dash by plotly (https://dash.plot.ly/gallery)    * Intuitive to use, elegant design  * Support interactive visualization* Bokeh (https://bokeh.pydata.org/en/latest/docs/gallery.html)  * Python interactive visualization for web browsers   * plotnice (aka. ggplot2) (https://plotnine.readthedocs.io/en/stable/index.html)  * `plotnine` is an implementation of a grammar of graphics in Python  * based on ggplot2, the most popular libry used in with the R language      Matplotlib: a Brief Intro* `Matplotlib` can be overwhelming, a good place to start is the gallery (https://matplotlib.org/gallery.html) * A multitude of plots to use for different scenarios* `matplotlib`'s main module is `pyplot`  * Imported using the `plt` alias```pythonimport matplotlib.pyplot as plt```  Matplotlib: Plotting with X and Y axes```python import matplotlib.pyplot as pltx = [1,2,3,5,6,7,8,9,10]y = [1,2,3,5,6,7,8,9,10]plt.plot(x, y)```<jupyter_code>y = [1.9**i for i in x ]
plt.plot(x, y)<jupyter_output><empty_output><jupyter_text>Plot Figure and Axes*  Plots in Matplotlib reside within a Figure object  * A figure contains the overall window where plotting happens    * Contains the title axes, labels, ticks, etc..```python    plt.figure()```* Figures are empty by default. Therefore, you need to add a axes (plot) to visualize your data* To add a plot, you need to determine the geometry and indicate where you want the plot to go   * This returns the axes of a new subplot. It's an object of type `AxesSubplot````pythonfig.axes(rect) or fig.add_subplot(rect)```* Therefore, Figure and plot/subplot (axes) are two different things ![](https://www.dropbox.com/s/10yf6ok45wllpbr/fig_axes.png?dl=1)<jupyter_code>fig = plt.figure()
fig = plt.figure()
# add_axes takes a rectangle [x0, y0, width, height]
fig.add_axes([0, 0, 1,1])

fig = plt.figure()
# add_axes takes a rectangle [x0, y0, width, height]
ax = fig.add_axes([0, 0, 1,1])
ax.plot([1,2,3,4,5], [1,2,3,4,5])
fig = plt.figure()
ax = fig.add_subplot()
print(f"ax is of type {type(ax)}")

fig = plt.figure()
ax = fig.add_subplot()
ax.plot([1,2,3,4,5], [1,2,3,4,5])<jupyter_output><empty_output><jupyter_text>Plotting Steps* When you issue the command plt.plot(x, y ), the following happens  * Matplotlib uses the figure created in a cell or creates one if none exists  * Uses the last axes used or creates one if necessary```python  fig = plt.figure()ax = fig.add_subplot()ax.plot([1,2,3,4,5], [1,2,3,4,5])```* Is equivalent to```pythonplt.plot([1,2,3,4,5], [1,2,3,4,5])```<jupyter_code># automatically plot on any cerated figure and axis 
fig = plt.figure()
plt.plot([1,2,3,4,5], [1,2,3,4,5])
plt.plot([1,2,3,4,5], [1,4,9,16,25])<jupyter_output><empty_output><jupyter_text>Creating Multiple Subplots* It is possible to draw multiple plots (subplots) in one figure using the `subplots()` or `add_subplot()` functions  * Each subplot has its own setos axis.    * Subplot layout is organized in rows and columns * A subplot needs to know where in the row/column layout it belongs```pythonadd_subplot(num_rows, num_cols, position_of_subplot)   ```<jupyter_code># Sample data
x = [1,2,3,4,5]
y_1 = [1,2,3,4,5]
y_2 = [i**2 for i in x]
y_3 = [i**3 for i in x]
y_4 = [i**4 for i in x]

x, y_1, y_2, y_3, y_4
# creating the subplots
fig = plt.figure()

ax1 = fig.add_subplot(2,2,1) # equivalent ot  ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(2,2,2) # equivalent ot  ax1 = fig.add_subplot(222)
ax3 = fig.add_subplot(2,2,3) # equivalent ot  ax1 = fig.add_subplot(223)
# using add_subplot

fig = plt.figure()

ax1 = fig.add_subplot(2,2,1) # equivalent ot  ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(2,2,2) # equivalent ot  ax1 = fig.add_subplot(222)
ax3 = fig.add_subplot(2,2,3) # equivalent ot  ax1 = fig.add_subplot(223)

ax1.plot(x, y_1)
ax2.plot(x, y_2)
ax3.plot(x, y_3)

fig = plt.figure()

ax1 = fig.add_subplot(2,2,1) # equivalent ot  ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(2,2,4) # equivalent ot  ax1 = fig.add_subplot(224)

ax1.plot(x, y_1) 
ax2.plot(x, y_3) 

# plot uses the last plot used.
fig = plt.figure(figsize=(11,2))
ax1 = fig.add_subplot(1,2,1) # equivalent ot  ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(1,2,2) # equivalent ot  ax1 = fig.add_subplot(222)
_ = plt.plot(np.random.randn(50).cumsum(),  'k--')
# Using subplot()

plt.subplot(2,2,1)
plt.plot(x, y_1)

plt.subplot(2,2,2)
plt.plot(x, y_2)

plt.subplot(2,2,3)
plt.plot(x, y_3)

plt.subplot(2,2,4)
plt.plot(x, y_4)<jupyter_output><empty_output><jupyter_text>Creating an Array of Subplots* Creating an array of subplots is a common task* `matplotlib` includes a function that generates the fig and all the plots using a single function* The plots car share the same x-axis or y-axis, * Many other options to control the spacing padding, figure size, etc.<jupyter_code>fig, axes = plt.subplots(2,3, figsize=(14,6))
print(axes)

print("---------------------")

axes[0,0].plot(x, y_1)
axes[1,2].plot(x, y_4)<jupyter_output>[[<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]
 [<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]]
---------------------<jupyter_text>Basic Plotting Parameters - Cont'd* Plot have various functions to customize them* Options are either:  * plot specific    * e.g. plot size, plot title, x-axis lebel, witespace, legend etc.   * Line color, Line type (e.g.: dashed, width=2), Labels```pythonplt.plot(x,y, color='red', linestyle='--')```python<jupyter_code>y = [1.9**i for i in x ]
plt.plot(x,y, color='red', linestyle='-.', linewidth=4)<jupyter_output><empty_output><jupyter_text>Basic Plotting Parameters - Cont'd- In addition to the data, `plot` accepts a string abbreviating color and line style  - This is a convenience```python    plt.plot(x,y, 'rx')     or    plt.plot(x,y, 'k--')```* `plt.plot(x,y, 'k--')` can be expressed as `plt.plot(x,y, color='k', linestyle='--')`* You can also specify color using hex code<jupyter_code>y = 1.9**x 
plt.plot(x,y, 'k--')

y = 30*x + 4
plt.plot(x,y, 'rx')


y = 40*x + 4
plt.plot(x,y, color='#feb24c')<jupyter_output><empty_output><jupyter_text>Plot Legend* Adding legends is critical for identifying plot elements* The easiest way to add a legend is to pass a label when adding each  element and calling the legend() function on the plot  * the label can be a `latex` equation* The legend is placed on the plot in a way that interferes the least with the plot  * You can change the location of the legend manually<jupyter_code>plt.figure(figsize=(8,4))

y = [1.9**i for i in x]
plt.plot(x, y, 'k--', label= "$1.9^x$")

y = [30*i + 4 for i in x]
plt.plot(x, y, 'rx', label= "_no_legend_")


y = [40*i + 4 for i in x]
plt.plot(x ,y, color='#feb24c', label= "$ 40 \cdot x + 4$")

plt.legend()<jupyter_output><empty_output><jupyter_text>Plot Labels* The minimum required labels to describe a plot are meaningful `x` and `y` label, and a plot title* Axes can have a title, and so does the figure* Title and labels can be customized  * Change font type and size, color, etc.<jupyter_code>fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot()
_ = ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])

fig.suptitle('This a generic figure  title')
ax.set_title("This is some plot title")
ax.set_xlabel("A range of values")

# can you guess why I am using _ =  here?
_ = ax.set_ylabel("Some other range of values")<jupyter_output><empty_output><jupyter_text>Changing Style Via Presets* Matplot lib provides various style presets to improve the look and feel of the plots  * The presets control the fonts, the colors, borders and line widths, etc.  * See https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html!~[](https://www.dropbox.com/s/h8fcd13v06bkhyf/styles.png?dl=1)```pythonplt.style.use('seaborn-whitegrid')```<jupyter_code>plt.style.use('seaborn-whitegrid')
fig, axes = plt.subplots(2,3, sharex=True, sharey=True, figsize=(8,3))

axes[0,0].plot(x, y_3)
axes[1,2].plot(x, y_4)

# Do not plt any whitespace between the subplots
# useful when sharing x and/or y
# used when it makes sense
plt.subplots_adjust(wspace=0, hspace=0)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1429372197309417, 'fraction_numerical': 0.03486547085201794, 'mean_word_length': 4.904037061548643, 'pattern_counts': {'":': 0, '<': 46, '<?xml version=': 0, '>': 46, 'https://': 9, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '50215', 'license': 'Apache-2.0', 'n_tokens_mistral': 3470, 'n_tokens_neox': 3263, 'n_words': 1009, 'path': 'morea/Data Viz/resources/.ipynb_checkpoints/data_vis_1-checkpoint.ipynb', 'repo_name': 'mahdi-b/ICS434-Sp2022', 'size': '8920'}