ContourPlot#

class metpy.plots.ContourPlot(**kwargs: Any)[source]#

Make contour plots by defining specific traits.

Attributes Summary

clabels

A boolean (True/False) on whether to plot contour labels.

contours

A list of values to contour or an integer number of contour levels.

cross_validation_lock

A contextmanager for running a block with our cross validation lock set to True.

data

Xarray dataset that contains the field to be plotted.

field

Name of the field to be plotted.

griddata

Return the internal cached data.

label_fontsize

An integer, float, or string value to set the font size of labels for contours.

latitude

The latitude coordinate of the field to be plotted.

level

The level of the field to be plotted.

linecolor

A string value to set the color of plotted contours; default is black.

linestyle

A string value to set the linestyle (e.g., dashed), or None; default is None, which, when using monochrome line colors, uses solid lines for positive values and dashed lines for negative values.

linewidth

An integer value to set the width of plotted contours; default value is 2.

longitude

The longitude coordinate of the field to be plotted.

mpl_args

Supply a dictionary of valid Matplotlib keyword arguments to modify how the plot variable is drawn.

name

Generate a name for the plot.

parent

A trait whose value must be an instance of a specified class.

plot_units

The desired units to plot the field in.

plotdata

Return the data for plotting.

scale

Scale the field to be plotted by the value given.

smooth_contour

Spline interpolation to smooth contours.

smooth_field

Number of smoothing passes using 9-pt smoother.

time

Set the valid time to be plotted as a datetime object.

x

The x coordinate of the field to be plotted.

y

The y coordinate of the field to be plotted.

Methods Summary

__init__(*args, **kwargs)

add_traits(**traits)

Dynamically add trait attributes to the HasTraits instance.

class_own_trait_events(name)

Get a dict of all event handlers defined on this class, not a parent.

class_own_traits(**metadata)

Get a dict of all the traitlets defined on this class, not a parent.

class_trait_names(**metadata)

Get a list of all the names of this class' traits.

class_traits(**metadata)

Get a dict of all the traits of this class.

clear()

Clear the plot.

clear_collections()

Clear the handle collections to the plot instance.

clear_handle()

Clear the handle to the plot instance.

copy()

Return a copy of the plot.

draw()

Draw the plot.

has_trait(name)

Returns True if the object has a trait with the specified name.

hold_trait_notifications()

Context manager for bundling trait change notifications and cross validation.

notify_change(change)

Notify observers of a change event

observe(handler[, names, type])

Setup a handler to be called when a trait changes.

on_trait_change([handler, name, remove])

DEPRECATED: Setup a handler to be called when a trait changes.

set_trait(name, value)

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs)

This is called before self.__init__ is called.

trait_defaults(*names, **metadata)

Return a trait's default value or a dictionary of them

trait_events([name])

Get a dict of all the event handlers of this class.

trait_has_value(name)

Returns True if the specified trait has a value.

trait_metadata(traitname, key[, default])

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this class' traits.

trait_values(**metadata)

A dict of trait names and their values.

traits(**metadata)

Get a dict of all the traits of this class.

unobserve(handler[, names, type])

Remove a trait change handler.

unobserve_all([name])

Remove trait change handlers of any type for the specified name.

Attributes Documentation

clabels#

A boolean (True/False) on whether to plot contour labels.

To plot contour labels set this trait to True, the default value is False.

contours#

A list of values to contour or an integer number of contour levels.

This parameter sets contour or colorfill values for a plot. Values can be entered either as a Python range instance, a list of values or as an integer with the number of contours to be plotted (as per matplotlib documentation). A list can be generated by using square brackets or creating a numpy 1D array and converting it to a list with the tolist method.

cross_validation_lock[source]#

A contextmanager for running a block with our cross validation lock set to True.

At the end of the block, the lock’s value is restored to its value prior to entering the block.

data[source]#

Xarray dataset that contains the field to be plotted.

field#

Name of the field to be plotted.

This is the name of the variable from the dataset that is to be plotted. An example, from a model grid file that uses the THREDDS convention for naming would be Geopotential_height_isobaric or Temperature_isobaric. For GOES-16/17 satellite data it might be Sectorized_CMI. To check for the variables available within a dataset, list the variables with the following command assuming the dataset was read using xarray as ds, list(ds)

griddata[source]#

Return the internal cached data.

label_fontsize#

An integer, float, or string value to set the font size of labels for contours.

This trait sets the font size for labels that will plot along contour lines. Accepts size in points or relative size. Allowed relative sizes are those of Matplotlib: ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’.

latitude#

The latitude coordinate of the field to be plotted.

This is a value with units to choose a desired latitude coordinate. For example, selecting a point or transect through 40 degrees north, set this parameter to 40 * units.degrees_north. Note that this requires your data to have a latitude dimension coordinate.

level#

The level of the field to be plotted.

This is a value with units to choose a desired plot level. For example, selecting the 850-hPa level, set this parameter to 850 * units.hPa. Note that this requires your data to have a vertical dimension coordinate.

linecolor#

A string value to set the color of plotted contours; default is black.

This trait can be set to any Matplotlib color (https://matplotlib.org/3.1.0/gallery/color/named_colors.html)

linestyle#

A string value to set the linestyle (e.g., dashed), or None; default is None, which, when using monochrome line colors, uses solid lines for positive values and dashed lines for negative values.

The valid string values are those of Matplotlib which are ‘solid’, ‘dashed’, ‘dotted’, and ‘dashdot’, as well as their short codes (‘-’, ‘–’, ‘.’, ‘-.’). The object None, as described above, can also be used.

linewidth#

An integer value to set the width of plotted contours; default value is 2.

This trait changes the thickness of contour lines with a higher value plotting a thicker line.

longitude#

The longitude coordinate of the field to be plotted.

This is a value with units to choose a desired longitude coordinate. For example, selecting a point or transect through 95 degrees west, set this parameter to -95 * units.degrees_east. Note that this requires your data to have a longitude dimension coordinate.

mpl_args#

Supply a dictionary of valid Matplotlib keyword arguments to modify how the plot variable is drawn.

Using this attribute you must choose the appropriate keyword arguments (kwargs) based on what you are plotting (e.g., contours, color-filled contours, image plot, etc.). This is available for all plot types (ContourPlot, FilledContourPlot, RasterPlot, ImagePlot, BarbPlot, ArrowPlot, PlotGeometry, and PlotObs). For PlotObs, the kwargs are those to specify the StationPlot object. NOTE: Setting the mpl_args trait will override any other trait that corresponds to a specific kwarg for the particular plot type (e.g., linecolor, linewidth).

name[source]#

Generate a name for the plot.

parent#

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

Subclasses can declare default classes by overriding the klass attribute

plot_units#

The desired units to plot the field in.

Setting this attribute will convert the units of the field variable to the given units for plotting using the MetPy Units module.

plotdata[source]#

Return the data for plotting.

The two dimension coordinates and the data array.

scale#

Scale the field to be plotted by the value given.

This attribute will scale the field by multiplying by the scale. For example, to scale vorticity to be whole values for contouring you could set the scale to 1e5, such that the data values will be multiplied by 10^5.

smooth_contour#

Spline interpolation to smooth contours.

This attribute requires settings for the metpy.calc.zoom_xarray function, which will produce a spline interpolation given an integer zoom factor. Either a single integer specifying the zoom factor (e.g., 4) or a tuple containing two integers for the zoom factor and the spline interpolation order can be used. The default spline interpolation order is 3.

This is best used to smooth contours when contouring a sparse grid (e.g., when your data has a large grid spacing).

smooth_field#

Number of smoothing passes using 9-pt smoother.

By setting this parameter with an integer value it will call the MetPy 9-pt smoother and provide a smoothed field for plotting. It is best to use this smoothing for data with finer resolutions (e.g., smaller grid spacings with a lot of grid points).

time#

Set the valid time to be plotted as a datetime object.

If a forecast hour is to be plotted the time should be set to the valid future time, which can be done using the datetime and timedelta objects from the Python standard library. Note that this requires your data to have a time dimension coordinate.

x#

The x coordinate of the field to be plotted.

This is a value with units to choose a desired x coordinate. For example, selecting a point or transect through the projection origin, set this parameter to 0 * units.meter. Note that this requires your data to have an x dimension coordinate.

y#

The y coordinate of the field to be plotted.

This is a value with units to choose a desired x coordinate. For example, selecting a point or transect through the projection origin, set this parameter to 0 * units.meter. Note that this requires your data to have an y dimension coordinate.

Methods Documentation

__init__(*args: Any, **kwargs: Any) None[source]#
add_traits(**traits: Any) None[source]#

Dynamically add trait attributes to the HasTraits instance.

classmethod class_own_trait_events(name: str) dict[str, EventHandler][source]#

Get a dict of all event handlers defined on this class, not a parent.

Works like event_handlers, except for excluding traits from parents.

classmethod class_own_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traitlets defined on this class, not a parent.

Works like class_traits, except for excluding traits from parents.

classmethod class_trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

clear()[source]#

Clear the plot.

Resets all internal state and sets need for redraw.

clear_collections()[source]#

Clear the handle collections to the plot instance.

clear_handle()[source]#

Clear the handle to the plot instance.

copy()[source]#

Return a copy of the plot.

draw()[source]#

Draw the plot.

has_trait(name: str) bool[source]#

Returns True if the object has a trait with the specified name.

hold_trait_notifications() Any[source]#

Context manager for bundling trait change notifications and cross validation.

Use this when doing multiple trait assignments (init, config), to avoid race conditions in trait notifiers requesting other trait values. All trait notifications will fire after all values have been assigned.

notify_change(change: Bunch) None[source]#

Notify observers of a change event

observe(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Parameters:
  • handler (callable) – A callable that is called when a trait changes. Its signature should be handler(change), where change is a dictionary. The change dictionary at least holds a ‘type’ key. * type: the type of notification. Other keys may be passed depending on the value of ‘type’. In the case where type is ‘change’, we also have the following keys: * owner : the HasTraits instance * old : the old value of the modified trait attribute * new : the new value of the modified trait attribute * name : the name of the modified trait attribute.

  • names (list, str, All) – If names is All, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

  • type (str, All (default: 'change')) – The type of notification to filter by. If equal to All, then all notifications are passed to the observe handler.

on_trait_change(handler: EventHandler | None = None, name: Sentinel | str | None = None, remove: bool = False) None[source]#

DEPRECATED: Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

If remove is True and handler is not specified, all change handlers for the specified name are uninstalled.

Parameters:
  • handler (callable, None) – A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self).

  • name (list, str, None) – If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

  • remove (bool) – If False (the default), then install the handler. If True then unintall it.

set_trait(name: str, value: Any) None[source]#

Forcibly sets trait attribute, including read-only attributes.

setup_instance(**kwargs: Any) None[source]#

This is called before self.__init__ is called.

trait_defaults(*names: str, **metadata: Any) dict[str, Any] | Sentinel[source]#

Return a trait’s default value or a dictionary of them

Notes

Dynamically generated default values may depend on the current state of the object.

classmethod trait_events(name: str | None = None) dict[str, EventHandler][source]#

Get a dict of all the event handlers of this class.

Parameters:

name (str (default: None)) – The name of a trait of this class. If name is None then all the event handlers of this class will be returned instead.

Returns:

The event handlers associated with a trait name, or all event handlers.

trait_has_value(name: str) bool[source]#

Returns True if the specified trait has a value.

This will return false even if getattr would return a dynamically generated default value. These default values will be recognized as existing only after they have been generated.

Example

class MyClass(HasTraits):
    i = Int()


mc = MyClass()
assert not mc.trait_has_value("i")
mc.i  # generates a default value
assert mc.trait_has_value("i")
trait_metadata(traitname: str, key: str, default: Any = None) Any[source]#

Get metadata values for trait by key.

trait_names(**metadata: Any) list[str][source]#

Get a list of all the names of this class’ traits.

trait_values(**metadata: Any) dict[str, Any][source]#

A dict of trait names and their values.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

Returns:

A dict of trait names and their values.

Notes

Trait values are retrieved via getattr, any exceptions raised by traits or the operations they may trigger will result in the absence of a trait value in the result dict.

traits(**metadata: Any) dict[str, TraitType[Any, Any]][source]#

Get a dict of all the traits of this class. The dictionary is keyed on the name and the values are the TraitType objects.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

The metadata kwargs allow functions to be passed in which filter traits based on metadata values. The functions should take a single value as an argument and return a boolean. If any function returns False, then the trait is not included in the output. If a metadata key doesn’t exist, None will be passed to the function.

unobserve(handler: Callable[[...], Any], names: Sentinel | str | Iterable[Sentinel | str] = traitlets.All, type: Sentinel | str = 'change') None[source]#

Remove a trait change handler.

This is used to unregister handlers to trait change notifications.

Parameters:
  • handler (callable) – The callable called when a trait attribute changes.

  • names (list, str, All (default: All)) – The names of the traits for which the specified handler should be uninstalled. If names is All, the specified handler is uninstalled from the list of notifiers corresponding to all changes.

  • type (str or All (default: 'change')) – The type of notification to filter by. If All, the specified handler is uninstalled from the list of notifiers corresponding to all types.

unobserve_all(name: str | Any = traitlets.All) None[source]#

Remove trait change handlers of any type for the specified name. If name is not specified, removes all trait notifiers.

Examples using metpy.plots.ContourPlot#

Combined Plotting

Combined Plotting

MetPy Declarative Syntax Tutorial

MetPy Declarative Syntax Tutorial