<jupyter_start><jupyter_text>![](../images/logos.jpg "MiCMOR, KIT Campus Alpin")**[MiCMOR](https://micmor.kit.edu) [SummerSchool "Environmental Data Science: From Data Exploration to Deep Learning"](https://micmor.kit.edu/sites/default/files/MICMoR%20Summer%20School%202019%20Flyer.pdf)**  IMK-IFU KIT Campus Alpin, Sept. 4 - 13 2019, Garmisch-Partenkirchen, Germany.---  Basic plotting in Python: Matplotlib**Note:** Parts of this notebook are inspired by the Notebook of Chapter 9 of the excellent [Python for Data Analysis Book](https://www.oreilly.com/library/view/python-for-data/9781491957653/) by <NAME> (the creator of pandas).The original notebook is located [here](https://nbviewer.jupyter.org/github/pydata/pydata-book/blob/2nd-edition/ch09.ipynb).The core plotting layer for most python plotting libs is [matplotlib](https://matplotlib.org). Initially, it was modeled after the Matlab plotting routines. It's beenaround for a long time and is very solid but may seem a bit clunky at first.Some of the more modern packages have nicer visuals by default, but you can tweakmatplotlib a lot and can also make it look more modern. Furthermore, a lot of the other packages will use matplotlib as a back-end. This is nice since you then can alterthem as you would with pure matplotlib plots.What also makes it a bit confusing for newcomers is a) that it's pretty low level and that b)it can be used with two paradigms: the matlab-style state-based model and the object-oriented (OO) model.<jupyter_code>%matplotlib inline
%load_ext autoreload
%autoreload 2
import matplotlib.pylab as plt
import numpy as np<jupyter_output><empty_output><jupyter_text>The two Matplotlib Plotting APIsJust a brief comparison... MATLAB-style stateful plotting flavorThis interface is stateful (it keeps track of the "current" figure and axes, you can get a reference to them with `plt.gcf()` (get current figure) and `plt.gca()` (get current axes).The interface is fast and convenient for simple plots. However, it can be nasty for more complex pots (i.e. mulitple panels). IMHO, do not use this for your work. The OO-style is almost as easy to use and much more powerful... However, you often might want to mix it in so it's good to know.<jupyter_code># some data
x = np.linspace(0, 10, 100)

# create a plot figure
plt.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>Object-oriented flavor<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 object
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));<jupyter_output><empty_output><jupyter_text>The Basics**Note:** It's quite common to mix and match the two interface styles. Figures and subplotsAs you can see, we always start with `figure`, `subplot` and `axes` objects. You can think of figureas the canvas and axes as an individual plot with its x/y-axis, ticks, labels and the actual plots. A figure can be composed by multiple subplots which each being addressed by its own axis.<jupyter_code># the manual way to compose a figure with three subplots
fig = plt.figure()
# the numbers are: row, column, number of plot
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)<jupyter_output><empty_output><jupyter_text>Matlotlib (MPL) uses a code to represent linestyle, cymbols or color. Here, we want a black (`k`) dashed (`--`) line.<jupyter_code>plt.plot(np.random.randn(50).cumsum(), 'k--');<jupyter_output><empty_output><jupyter_text>Now we do a more complicated plot. It is composed of two subplots, with a histogram on the left and a scatter plot on the right. We specify a plot size of 14x4 inches.We also use 20 bins for the histogram and fill the bars with black (30% opacity).<jupyter_code>fig = plt.figure(figsize=(14,4))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30));
plt.close('all')<jupyter_output><empty_output><jupyter_text>A more common way to create a figure with subplots is:```pythonfig, axes = plt.subplots(2, 3)```This would create a figure with 6 subplots (2 rows, 3 columns).Now, let's compose a 2x2 plot with shared axes and histograms. We also adjust the space between the plots for a more compact plot.<jupyter_code>fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
    for j in range(2):
        axes[i, j].hist(np.random.randn(500), bins=50, color='k', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)<jupyter_output><empty_output><jupyter_text>Colors, Markers and line stylesAs mentioned above, you can adjust markers and styles with a special syntax. `ko--` would create a ine plot (dashed) with marker circles in black.<jupyter_code>from numpy.random import randn
plt.plot(randn(30).cumsum(), 'ko--');
plt.close('all')<jupyter_output><empty_output><jupyter_text>You can combine multiple plots into an axis and create a legend that's composed from labels attached to the plot commands...<jupyter_code>data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
plt.legend(loc='best');<jupyter_output><empty_output><jupyter_text>Ticks, labels and legendsSe can customize all parts of the plots. I.e., we can set custom ticks and labels.<jupyter_code>fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

# now we define custom tick positions and tick labels
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
                            rotation=30, fontsize='small')

# set a title and an axis label
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages');<jupyter_output><empty_output><jupyter_text>As previously shown above, it's easy to add legends (see the guide [[here]](https://matplotlib.org/3.1.1/tutorials/intermediate/legend_guide.html) for more details...<jupyter_code>from numpy.random import randn
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(randn(1000).cumsum(), 'k', label='one')
ax.plot(randn(1000).cumsum(), 'k--', label='two')
ax.plot(randn(1000).cumsum(), 'k.', label='three');

# add legend to the best location (repart the plot by
# running the cell multiple times to see it in action)
ax.legend(loc='best');<jupyter_output><empty_output><jupyter_text>Saving files to diskIt's easy to save the figure to disc. You can specify the file type to `pdf` or `png`:```python plot my stuff, then...plt.savefig('figure.png', dpi=400, bbox_inches='tight') and as a pdfplt.savefig('figure.pdf', bbox_inches='tight')````bbox_inches='tight'` is required to avoid unnecessary whitespace around figures...  Change the plot styleAs this is a common complaint about matplotlib: you can actually style your plots in matplotlib. ```pythonplt.style.use('seaborn-whitegrid')```Below are some examples (source - also click for more examples: https://matplotlib.org/3.1.1/gallery/style_sheets/style_sheets_reference.html):![](https://matplotlib.org/3.1.1/_images/sphx_glr_style_sheets_reference_001.png)![](https://matplotlib.org/3.1.1/_images/sphx_glr_style_sheets_reference_026.png)![](https://matplotlib.org/3.1.1/_images/sphx_glr_style_sheets_reference_006.png) And a note on confusing differences in the API.Consider this simple plot:<jupyter_code>x = np.linspace(0, 10, 30)
y = np.sin(x)

plt.plot(x, y, 'o', color='black');<jupyter_output><empty_output><jupyter_text>Matplotlib can be used with a bit of an archaic syntax for specifying linstyles, symbols and colors in very short argument form.Take a look at this example:<jupyter_code>plt.plot(x, y, 'o-k');<jupyter_output><empty_output><jupyter_text>This could also be written as:<jupyter_code>plt.plot(x, y, 'o', ls='-', c='k');<jupyter_output><empty_output><jupyter_text>Or even more verbose (but actually readable):<jupyter_code>plt.plot(x, y, 'o', linestyle='-', color='black');<jupyter_output><empty_output><jupyter_text>Use scatter instead of plot if you want to control aspects of the points with data...<jupyter_code>rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)

plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
            cmap='viridis')
plt.colorbar();  # show color scale<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.124364896073903, 'fraction_numerical': 0.024595842956120093, 'mean_word_length': 5.401330376940133, 'pattern_counts': {'":': 0, '<': 66, '<?xml version=': 0, '>': 66, 'https://': 10, 'lorem ipsum': 0, 'www.': 1, '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': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '24544', 'license': 'Apache-2.0', 'n_tokens_mistral': 3128, 'n_tokens_neox': 2868, 'n_words': 960, 'path': 'nbs/03_intro_matplotlib.ipynb', 'repo_name': 'SteveMHill/kit_micmor_summerschool_2019', 'size': '8666'}