<jupyter_start><jupyter_text>*This notebook is part of  course materials for CS 345: Machine Learning Foundations and Practice at Colorado State University.Original versions were created by <NAME>.The content is availabe [on GitHub](https://github.com/asabenhur/CS345).**The text is released under the [CC BY-SA license](https://creativecommons.org/licenses/by-sa/4.0/), and code is released under the [MIT license](https://opensource.org/licenses/MIT).*     Data visualization with Matplotlib Matplotlib is the "standard" Python data visualization library.It was originally conceived to provide an alternative to Matlab, and some of its syntax derived from that.  In recent years, it has begun to show its age, and other packages that build on it provide cleaner, more modern APIs.For example, [seaborn](https://seaborn.pydata.org/), [HoloViews](http://holoviews.org/), [Altair](http://altair-viz.github.io/), and [pandas](https://pandas.pydata.org/) can be used as wrappers for Matplotlib.However, it is still a good place to start.  Importing MatplotlibWe will use the standard shorthand for importing Matplotlib:<jupyter_code>import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>The `pyplot` API is the one we will most generally use.  Matplotlib in the Jupyter notebookDisplaying Matplotlib in a Jupyter notebook can be done with the ``%matplotlib`` command.  The argument to this command chooses which Matplotlib backend to use.We will generally use it as ``%matplotlib inline`` which generates static images that are embedded in the notebook.The other relevant option for Jupyter notebooks is ``%matplotlib notebook`` which will generate *interactive* plots.<jupyter_code>%matplotlib inline<jupyter_output><empty_output><jupyter_text>We are now ready to generate our first plot:<jupyter_code>import numpy as np
x = np.linspace(0, 10, 100)

fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');<jupyter_output><empty_output><jupyter_text>Saving to fileYou can save your Matplotlib figure to a file using the ``savefig()`` command.The extension used will determine the format.  For example:<jupyter_code>fig.savefig('my_figure.png')<jupyter_output><empty_output><jupyter_text>We now have a file called ``my_figure.png`` in the current working directory:<jupyter_code>!ls -lh my_figure.png<jupyter_output>-rw-r--r--  1 asa  staff    22K Aug 29 11:47 my_figure.png<jupyter_text>The two interfaces of Matplotlib A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface.  The MATLAB-style InterfaceThe MATLAB-style API is contained in the pyplot (``plt``) module.For example, the following code will probably look quite familiar to MATLAB users:<jupyter_code>plt.figure()  # create a plot figure

# create the first of two panels and set current axis
plt.subplot(2, 1, 1) # (rows, columns, panel number)
plt.plot(x, np.sin(x))

# create the second panel and set current axis
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x));<jupyter_output><empty_output><jupyter_text>It is important to note that this interface is *stateful*: it keeps track of the "current" figure and axes, which are where all ``plt`` commands are applied.You can get a reference to these using ``plt.gcf()`` (get current figure) and ``plt.gca()`` (get current axes).While this stateful interface is fast and convenient for simple plots, it is easy to run into problems.For example, once the second panel is created, how can we go back and add something to the first?This is possible within the MATLAB-style interface, but a bit clunky.Fortunately, there is a better way.  Object-oriented interfaceThe object-oriented interface is available for these more complicated situations, and for when you want more control over your figure.Rather than depending on some notion of an "active" figure or axes, in the object-oriented interface the plotting functions are *methods* of explicit ``Figure`` and ``Axes`` objects.For example:<jupyter_code># first create a grid of plots
# ax will be an array of two Axes objects
fig, ax = plt.subplots(2)

# Call plot() method on the appropriate Axes object
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));<jupyter_output><empty_output><jupyter_text>Throughout this course, we will switch between the two interfaces, depending on what is most convenient.  Scatter plotsScatter plots are one of our "bread-and-butter" methods for visualizing data in two dimensions:<jupyter_code>from sklearn.datasets import make_classification
X,y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1, class_sep=0.4, random_state=1)
X.shape, y.shape
plt.scatter(X[:,0], X[:,1], c=y, alpha=0.5, s=50);<jupyter_output><empty_output><jupyter_text>The `s` parameter controls the size of the markers, and like the color parameter, `c`, it can be an array of values.We can achieve a similar result using `plt.plot`.  However, it does not have the same level of flexibility and it produces markers that are all the same color and size:<jupyter_code>plt.plot(X[:,0], X[:,1], 'ob', alpha=0.5);<jupyter_output><empty_output><jupyter_text>HistogramsAs an example we will generate two datasets from a normal distribution and plot their histograms, showing some features of Matplotlib's `hist` function.  The 'normed' flag normalizes the bin heights such that it represents a probability distribution.<jupyter_code>mu = 100
sigma = 15
x1 = mu + sigma * np.random.randn(100000)
x2 = mu + 25 + sigma * np.random.randn(100000)

num_bins = 50
plt.hist(x1, num_bins, density=True, facecolor='green', alpha=0.4, 
         edgecolor = 'black', label='hist1');
plt.hist(x2, num_bins, density=True, facecolor='blue', alpha=0.4, 
         edgecolor = 'black', label='hist2');
plt.xlabel('x',fontsize=12);
plt.ylabel('normalized counts', fontsize=12);
x = np.linspace(40, 180, 1000)
normal = (1/np.sqrt(2*np.pi*sigma**2))*np.exp(-(x-mu)**2/(2*sigma**2))
plt.plot(x, normal, '-k', label='normal1');

normal = (1/np.sqrt(2*np.pi*sigma**2))*np.exp(-(x-mu-25)**2/(2*sigma**2))
plt.plot(x, normal, '-b', label='normal2');

plt.legend(loc='upper left', fontsize='12');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11010342084327765, 'fraction_numerical': 0.018456642800318217, 'mean_word_length': 5.665959703075291, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 41, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, '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': '479851', 'license': 'MIT', 'n_tokens_mistral': 2056, 'n_tokens_neox': 1935, 'n_words': 712, 'path': 'notebooks/module01_05_matplotlib.ipynb', 'repo_name': 'lottieandrews/CS345', 'size': '6290'}