This script illustrates the following concepts:
  • Drawing bars instead of curves in an XY plot

  • Changing the width of the bars in a bar plot

  • Drawing filled bars up or down based on a Y reference value

  • Setting the minimum/maximum value of the Y axis in a bar plot

See following URLs to see the reproduced NCL plot & script:

Import packages

import numpy as np
import xarray as xr
import matplotlib.pyplot as plt

import geocat.datafiles as gdf
import geocat.viz as gv

Read in data:

# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/"))
dsoik = ds.DSOI_KET
date =
num_months = np.shape(date)[0]

# Dates in the file are represented by year and month (YYYYMM)
# representing them fractionally will make plotting the data easier
# This produces the same results as NCL's yyyymm_to_yyyyfrac() function
date_frac = np.empty_like(date)
for n in np.arange(0, num_months, 1):
    yyyy = int(date[n] / 100)
    mon = (date[n] / 100 - yyyy) * 100
    date_frac[n] = yyyy + (mon - 1) / 12


# Generate figure (set its size (width, height) in inches) and axes
plt.figure(figsize=(12, 6))
ax = plt.axes()

# Create a list of colors based on the color bar values
colors = ['red' if (value > 0) else 'blue' for value in dsoik[::8]]

# Plot bar chart with defined width[::8], dsoik[::8], color=colors, width=0.25)

# Use geocat.viz.util convenience function to add minor and major tick lines

# Use geocat.viz.util convenience function to set axes parameters
                             ylim=(-3, 3),
                             yticks=np.linspace(-3, 3, 7),
                             yticklabels=np.linspace(-3, 3, 7),
                             xlim=(date_frac[40], date_frac[-16]),
                             xticks=np.linspace(1900, 1980, 5))

# Use geocat.viz.util convenience function to set titles and labels
                         maintitle="Darwin Southern Oscillation Index",

# Plot horizontal line as a reference
plt.hlines(0, 1880, 2000, colors="black", linewidth=.6)

Darwin Southern Oscillation Index

Total running time of the script: (0 minutes 1.115 seconds)

Gallery generated by Sphinx-Gallery