Plot Elements

Prerequisites

Concepts

Importance

Notes

Matplotlib

Necessary

Cartopy

Necessary

  • Time to learn: 40 minutes


import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import geocat.viz as gv

Data

The first piece of data visualization is the data!

Let’s generate some dummy data to work with:

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

Figure

The figure is the object that contains your entire visualization. Creating a figure tends to be the first step in plotting, even if it doesn’t currently show anything:

fig = plt.figure(figsize=(9.5, 8))
<Figure size 950x800 with 0 Axes>

Axis

We then add axes to our plot. You can add multiple axes to one plot in order to produce subplots, or just one. Axes will automatically inherit their limits from the data plotted, or can be manually set.

fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()
../_images/a38bbe9524718c5f11c5238365f7fd042a36c6f7191d6a7d418b1e33b4fdc157.png

Plot

Adding the data to the figure can be done through several different plot types: line, contour, bar, histogram. Here we use two line plots:

fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()

ax.plot(x,y1)
ax.plot(x,y2);
../_images/6322bf96868bb27a39841e44c0e51741aaabd00d4ef59b71e232855b2cd59d8e.png

Titles and Labels

Titles and labels are important for indicating what the figure is plotting. It is a good idea to include relevant units in your axis labels.

fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()

ax.plot(x,y1)
ax.plot(x,y2)

ax.set_title("Dummy Data")
ax.set_xlabel("X (radians)");
../_images/6e17ed65e190b703e236745dcb532ffaf8389615c697374186dc37d55bf89c96.png

Legends

If you’re plotting multiple lines of data, it’s a good idea to include a legend. Here is how you call or point to the legend:

fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()

ax.plot(x,y1,label='sine')
ax.plot(x,y2,label='cosine')

ax.set_title("Dummy Data")
ax.set_xlabel("X (radians)")

plt.legend(loc="upper left");
../_images/9840fa29f9678a0a2c63031eec163beac5f17fe23a85bf9904631003ff045b8c.png

Colorbars

While legends are more appropriate for line or bar plots, colorbars are most commonly used for contour plots and sometimes to apply a third level of dimension to a scatter plot.

Let’s shift our example to better demonstrate a colorbar by workign with a filled contour plot:

# Generate dummy data
data = [[1, 4, 5, 6, 8.2],
        [9, 8.4, 10, 10.6, 9.7],
        [4.4, 5, 0, 6.6, 1.4],
        [4.6, 5.2, 1.5, 7.6, 2.4]]

# Convert data into type xarray.DataArray
data = xr.DataArray(data,
                    dims=["lat", "lon"],
                    coords=dict(lat=np.arange(4), lon=np.arange(5)))

data
<xarray.DataArray (lat: 4, lon: 5)> Size: 160B
array([[ 1. ,  4. ,  5. ,  6. ,  8.2],
       [ 9. ,  8.4, 10. , 10.6,  9.7],
       [ 4.4,  5. ,  0. ,  6.6,  1.4],
       [ 4.6,  5.2,  1.5,  7.6,  2.4]])
Coordinates:
  * lat      (lat) int64 32B 0 1 2 3
  * lon      (lon) int64 40B 0 1 2 3 4
fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()

pcm = ax.contourf(data,cmap='viridis')

ax.set_title("Dummy Data")
ax.set_xlabel("Longitude (\N{DEGREE SIGN})")
ax.set_ylabel("Latitude (\N{DEGREE SIGN})")

fig.colorbar(pcm,ax=ax);
../_images/566a26e603f853d157bbd9d6058b03aefc2e0a05e372515d4044da7af8f8759b.png

Annotations

Additional annotations allow you to specify some text and a location to indicate almost anything.

Here we use GeoCAT-viz to add annotations to the maxima in a contour plot:

fig = plt.figure(figsize=(9.5, 8))
ax = plt.axes()

pcm = ax.contourf(data,cmap='viridis')

ax.set_title("Dummy Data")
ax.set_xlabel("Longitude (\N{DEGREE SIGN})")
ax.set_ylabel("Latitude (\N{DEGREE SIGN})")

fig.colorbar(pcm,ax=ax)

# Find local maximum with GeoCAT-Viz find_local_extrema
lmax = gv.find_local_extrema(data, eType='High')[0]

# Plot labels for local mins
max_value = data.data[lmax[1]][lmax[0]]
ax.text(lmax[0], lmax[1],'Maxima = '+str(max_value))

# Show plot
plt.show();
../_images/4092d4629ef5f978c76be6a24cf4006ac3190c95d7a37cb93d10ae36cd59f873.png

Summary

There are several key elements to a Python plot and knowing what they are called is instrumental to begin your journey for further customization.

What’s next?

Next up, the specialty plots called Taylor Diagrams.

Resources and references