<jupyter_start><jupyter_text>Getting Started with MatplotlibWe need `matplotlib.pyplot` for plotting.<jupyter_code>import matplotlib.pyplot as plt
import pandas as pd<jupyter_output><empty_output><jupyter_text>About the DataIn this notebook, we will be working with 2 datasets:- Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis))- Earthquake data from September 18, 2018 - October 13, 2018 (obtained from the US Geological Survey (USGS) using the [USGS API](https://earthquake.usgs.gov/fdsnws/event/1/))  Plotting lines<jupyter_code>fb = pd.read_csv(
    'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True
)

plt.plot(fb.index, fb.open)
plt.show()<jupyter_output><empty_output><jupyter_text>Since we are working in a Jupyter notebook, we can use the magic command `%matplotlib inline` once and not have to call `plt.show()` for each plot.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd

fb = pd.read_csv(
    'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True
)
plt.plot(fb.index, fb.open)<jupyter_output><empty_output><jupyter_text>Scatter plots We can pass in a string specifying the style of the plot. This is of the form '[color][marker][linestyle]'. For example, we can make a black dashed line with `'k--'` or a red scatter plot with `'ro'`:<jupyter_code>plt.plot('high', 'low', 'ro', data=fb.head(20))<jupyter_output><empty_output><jupyter_text>Histograms<jupyter_code>quakes = pd.read_csv('data/earthquakes.csv')
plt.hist(quakes.query('magType == "ml"').mag)<jupyter_output><empty_output><jupyter_text>Bin size mattersNotice how our assumptions of the distribution of the data can change based on the number of bins (look at the drop between the two highest peaks on the righthand plot):<jupyter_code>x = quakes.query('magType == "ml"').mag
fig, axes = plt.subplots(1, 2, figsize=(10, 3))
for ax, bins in zip(axes, [7, 35]):
    ax.hist(x, bins=bins)
    ax.set_title(f'bins param: {bins}')<jupyter_output><empty_output><jupyter_text>Plot components `Figure`Top-level object that holds the other plot components.<jupyter_code>fig = plt.figure()<jupyter_output><empty_output><jupyter_text>`Axes`Individual plots contained within the `Figure`. Creating subplotsSimply specify the number of rows and columns to create:<jupyter_code>fig, axes = plt.subplots(1, 2)<jupyter_output><empty_output><jupyter_text>As an alternative to using `plt.subplots()` we can add the `Axes` to the `Figure` on our own. This allows for some more complex layouts, such as picture in picture:<jupyter_code>fig = plt.figure(figsize=(3, 3))
outside = fig.add_axes([0.1, 0.1, 0.9, 0.9])
inside = fig.add_axes([0.7, 0.7, 0.25, 0.25])<jupyter_output><empty_output><jupyter_text>Creating Plot Layouts with `gridspec`We can create subplots with varying sizes as well:<jupyter_code>fig = plt.figure(figsize=(8, 8))
gs = fig.add_gridspec(3, 3)
top_left = fig.add_subplot(gs[0, 0])
mid_left = fig.add_subplot(gs[1, 0])
top_right = fig.add_subplot(gs[:2, 1:])
bottom = fig.add_subplot(gs[2,:])<jupyter_output><empty_output><jupyter_text>Saving plotsUse `plt.savefig()` to save the last created plot. To save a specific `Figure` object, use its `savefig()` method.<jupyter_code>fig.savefig('empty.png')<jupyter_output><empty_output><jupyter_text>Cleaning upIt's important to close resources when we are done with them. We use `plt.close()` to do so. If we pass in nothing, it will close the last plot, but we can pass the specific `Figure` to close or say `'all'` to close all `Figure` objects that are open. Let's close all the `Figure` objects that are open with `plt.close()`:<jupyter_code>plt.close('all')<jupyter_output><empty_output><jupyter_text>Additional plotting options Specifying figure sizeJust pass the `figsize` parameter to `plt.figure()`. It's a tuple of (width, height):<jupyter_code>fig = plt.figure(figsize=(10, 4))<jupyter_output><empty_output><jupyter_text>This can be specified when creating subplots as well:<jupyter_code>fig, axes = plt.subplots(1, 2, figsize=(10, 4))<jupyter_output><empty_output><jupyter_text>`rcParams`A small subset of all the available plot settings (shuffling to get a good variation of options):<jupyter_code>import random
import matplotlib as mpl

rcparams_list = list(mpl.rcParams.keys())
random.seed(20) # make this repeatable
random.shuffle(rcparams_list)
sorted(rcparams_list[:20])<jupyter_output><empty_output><jupyter_text>We can check the current default `figsize` using `rcParams`:<jupyter_code>mpl.rcParams['figure.figsize']<jupyter_output><empty_output><jupyter_text>We can also update this value to change the default (until the kernel is restarted):<jupyter_code>mpl.rcParams['figure.figsize'] = (300, 10)
mpl.rcParams['figure.figsize']<jupyter_output><empty_output><jupyter_text>Use `rcdefaults()` to restore the defaults:<jupyter_code>mpl.rcdefaults()
mpl.rcParams['figure.figsize']<jupyter_output><empty_output><jupyter_text>This can also be done via `pyplot`:<jupyter_code>plt.rc('figure', figsize=(20, 20)) # change figsize default to (20, 20)
plt.rcdefaults() # reset the default<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12442307692307693, 'fraction_numerical': 0.018076923076923077, 'mean_word_length': 7.1265625, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 77, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '65656', 'license': 'MIT', 'n_tokens_mistral': 1929, 'n_tokens_neox': 1788, 'n_words': 485, 'path': 'ch_05/1-introducing_matplotlib.ipynb', 'repo_name': 'rvmuthukumar/Hands-On-Data-Analysis-with-Pandas', 'size': '5200'}