pyiem.plot package¶
Submodules¶
pyiem.plot.calendarplot module¶
Calendar Plot.
- pyiem.plot.calendarplot.calendar_plot(sts, ets, data, **kwargs)¶
Create a plot that looks like a calendar
- Parameters:
sts (datetime.date) – start date of this plot
ets (datetime.date) – end date of this plot (inclusive)
data (dict[dict]) – dictionary with keys of dates and dicts for val value and optionally color for color
kwargs (dict) – heatmap (bool): background color for cells based on val, False cmap (str): color map to use for norm apctx (dict): autoplot context.
pyiem.plot.colormaps module¶
Definition of colormaps
- pyiem.plot.colormaps.dep_erosion()¶
DEP Erosion ramp yelllow to brown (jump at 5T) cool
- pyiem.plot.colormaps.get_cmap(name)¶
Helper to workaround matplotlib complexity.
- pyiem.plot.colormaps.james()¶
David James suggested color ramp Yellow to Blue
- pyiem.plot.colormaps.james2()¶
David James suggested color ramp Yellow to Brown
- pyiem.plot.colormaps.maue()¶
Pretty color ramp Dr Ryan Maue uses
- pyiem.plot.colormaps.nwsice()¶
A Color Ramp Suggested by the NWS for Ice Accumulation.
- pyiem.plot.colormaps.nwsprecip()¶
A color ramp used by NWS on NTP plots
- Changes
modified the reds a bit to provide a larger gradient
added two light brown colors at the low end to allow for more levels
removed perhaps a bad orange color and remove top white color
- pyiem.plot.colormaps.nwssnow()¶
A Color Ramp Suggested by the NWS for Snowfall
- pyiem.plot.colormaps.radar_ptype() dict[str, list] ¶
Generate a dictionary of colors for HRRR Ptype.
- pyiem.plot.colormaps.stretch_cmap(cmap, bins, extend='both')¶
Return a cmap with appropriate over,under,bad settings.
The issue at hand is that default color ramps do not properly extend to cover over and under using values from the color ramp. That is desired behaviour of this library. If over,under,bad is already set, those settings are retained.
- Parameters:
cmap (cm.ColorMap) – inbound colormap
bins (list) – values for binning
extend (str) – either ‘both’, ‘neither’, ‘min’, ‘max’ to control cbar
- Retuns:
cm.ColorMap
- pyiem.plot.colormaps.whitebluegreenyellowred()¶
Rip off NCL’s WhiteBlueGreenYellowRed
pyiem.plot.geoplot module¶
Plotting utility for generating maps, windroses and everything else under the sun.
This module provides a wrapper around Basemap and windrose packages. It tries to be general so to work for others, but may contain some unfortunate hard coded values. Bad daryl!
Example
Here is a basic example of usage.
>>> from pyiem.plot.geoplot import MapPlot
>>> m = MapPlot(sector='conus', title='My Fancy Title')
>>> m.postprocess(filename='myplot.png')
>>> m.close()
- class pyiem.plot.geoplot.MapPlot(sector='iowa', **kwargs)¶
Bases:
object
An object representing a matplotlib figure.
An object that allows one to quickly and easily generate map plots of data with some customization possible. This is what drives most of the plots you see on the IEM website.
Example
Here is an example of usage:
mplot = MapPlot(sector='midwest', title='My Plot Title') mplot.plot_values([-99,-95], [44,45], ['hi','there']) mplot.postprocess(filename='test.png') mplot.close()
- fig¶
figure object
- Type:
matplotlib.Figure
- ax¶
main figure plot axes
- Type:
matplotlib.Axes
- close()¶
Close the figure in the case of batch processing
- contourf(lons, lats, vals, clevs, **kwargs)¶
Contourf
- Parameters:
ilabel (boolean,optional) – Should we label contours
iline (boolean,optional) – should we draw contour lines
lblformat (str,optional) – Format string for labeling contours, %.0f. draw_colorbar (bool,optional): Draw colorbar default True.
linewidths (float,optional) – Line width(s) for contour lines
- Returns:
The values used for plotting, maybe after gridding
- Return type:
vals (np.array)
- draw_colorbar(clevs, cmap, norm, **kwargs)¶
Draw the colorbar on the structed plot using self.cax.
- Parameters:
clevs (list) – The levels used in the classification
cmap (matplotlib.colormap) – The colormap
norm (normalize) – The value normalizer
title (str,optional) – Place a label on the side, adjusts the plot accordingly to allow this text to fit, no multiline please!
spacing (str,optional) – should the colorbar be uniform or proportional, defaults to uniform
- draw_cwas(color='k', **kwargs)¶
Overlay CWA Borders
Draw the CWA border lines on the map.
- Parameters:
color (str) – The color to draw the CWA borders with
kwargs (dict, optional) – Parameters passed to matplotlib for plotting
- draw_fema_regions(color: str = 'k', **kwargs)¶
Overlay FEMA Regions.
- draw_mask(sector=None)¶
Draw a mask on the main axes.
If sector is not provided, this attempts to intelligently to the masking the user wants.
- Parameters:
sector (str,optional) – Hard code what type of sector masking should happen.
- draw_radar_ptype_legend()¶
Draw a legend for radar precipitation type.
- draw_usdm(valid=None, filled=True, hatched=False, **kwargs)¶
Overlay the US Drought Monitor
This utilizes a GeoJSON web service provided by the IEM. The provided date to this method is passed to the web service which rectifies the date to provide the USDM analysis valid for that date. If no date is specified, the current analysis is plotted.
- Parameters:
valid (str or datetime.date) – The valid time to plot this USDM
filled (boolean) – Should we draw lines or filled polygons
hatched (boolean) – Should we use hatch filling
alpha (float) – Alpha value for the polygons, default 0.5.
- Returns:
date that the USDM is valid for
- drawcities(**kwargs)¶
Overlay some cities
- Parameters:
minpop (int,optional) – Minimum population to consider for plotting.
labelbuffer (int) – approximate number of pixels to compute overlap
textsize (int) – size of the text
color (str) – color to plot the text with
outlinecolor (str) – color to outline the text with
isolated (bool) – Cause plot_values to do label collision against only labels from drawing cities. Default False.
- drawcounties(color='k')¶
Draw counties onto the map
- Parameters:
color (color,optional) – line color to use
- fill_climdiv(data, **kwargs)¶
Fill climate divisions using provided data dictionary
- Parameters:
data (dict) – A dictionary of climate division IDs and values
- fill_cwas(data, **kwargs)¶
Add overlay of filled polygons for NWS Forecast Offices.
Method adds a colorized overlay of NWS Forecast Offices based on a data dictionary of values provided. This method also places a color bar on the image.
- Parameters:
data (dict) – Dictionary of values with keys representing the 3 char or 4 char idenitifer for the WFO. This assumes the 3 char sites are the K ones.
ilabel (bool) – Should we label?
- fill_cwsu(data, **kwargs)¶
Add overlay of filled polygons for NWS CWSUs.
Data is dictionary-ish.
- fill_fema_regions(data, **kwargs)¶
Add overlay of filled polygons for FEMA Regions.
Data is dictionary-ish and keys should be ints!
- fill_rfc(data, **kwargs)¶
Add overlay of filled polygons for NWS RFCs.
Data is dictionary-ish. Note that the ids used here are the WMO center IDs (ie TAR) and not basin ids (ie NERFC)
- fill_states(data, **kwargs)¶
Add overlay of filled state polygons
- fill_ugcs(data, **kwargs)¶
Overlay filled UGC geometries using bundled geometries.
Note the importance of the is_firewx flag. This determines which UGC database to look at in the face of ambiquity.
Note that this will fail when provided a data dictionary that has both zones and counties. It is recommended to plot from application logic with your own geometries in this instance.
- Parameters:
data (dict) – A dictionary of 6 char UGC code keys and values
bins (list, optional) – Bins to use for cloropleth, default 0:101:10
color (dict, optional) – Hard code what each UGC should display as for color.
is_firewx (bool, optional) – Are we plotting fire weather zones?
draw_colorbar (bool, optional) – Should a color bar be generated, default is True.
plotmissing (bool, optional) – Should missing UGC data be plotted?
labels (dict, optional) – UGC indexed dictionary to use for labeling.
lblformat (str, optional) – Format string for labels, default %s.
missingval (str, optional) – value to use when labelling UGCs with missing values, defaults to ‘-‘.
- hexbin(lons, lats, vals, clevs, **kwargs)¶
hexbin wrapper.
- Parameters:
draw_colorbar (bool,optional) – Draw colorbar default True.
- imshow(grid: ndarray, affine: Affine, crs: str, clevs: list | None = None, **kwargs)¶
Reprojects an image onto each MapPanel and then draws it.
- Parameters:
grid (np.ndarray) – The 2-D data to draw
affine (Affine) – The affine transformation of the image
crs (str) – The CRS of the image
clevs (list, Optional) – The levels to use for the colormap
- Keyword Arguments:
draw_colorbar (bool,optional) – Draw colorbar default True.
cmap (str,optional) – The colormap to use, default jet.
extend (str,optional) – The extend value for the colormap.
clip_on (bool,optional) – Clip the image to the map region.
- overlay_nexrad(valid=None, product='N0Q', caxpos=None)¶
Overlay an IEM NEXRAD Composite Image.
- Parameters:
valid (datetime.datetime) – Valid time for NEXRAD overlay.
product (str) – either N0Q or N0R for the mosaic type.
caxpos (array-like) – matplotlib.axes.set_position value for the colorbar. Defaults to something in the upper-right.
- Returns:
valid time of the NEXRAD, or None if not found.
- overlay_roadcond(valid=None)¶
Overlay Iowa Winter Road Conditions.
- Parameters:
valid (datetime.datetime) – Valid time for NEXRAD overlay.
- pcolormesh(lons, lats, vals, clevs, **kwargs)¶
Opinionated mpl.pcolormesh wrapper.
If you supply a lons in the same shape of the vals, this method will tack on an extra row and column to make matplotlib happy. If you do not want this, then pass your own lons + lats that is 1 column and 1 row greater than vals.
- Parameters:
draw_colorbar (bool,optional) – Draw colorbar default True.
- plot_station(data, **kwargs)¶
Plot values on a map in a station plot like manner.
- Parameters:
data (list) – list of dicts with station data to plot
fontsize (int) – font size to use for plotted text
- plot_values(lons, lats, vals, fmt='%s', valmask=None, color='#000000', textsize=14, labels=None, labeltextsize=10, labelcolor='#000000', showmarker=False, labelbuffer=25, outlinecolor='#FFFFFF', zorder=None, **kwargs)¶
Plot values onto the map
- Parameters:
lons (list) – longitude values to use for placing vals
lats (list) – latitude values to use for placing vals
vals (list) – actual values to place on the map
fmt (str, optional) – Format specification to use for representing the values. For example, the default is ‘%s’.
valmask (list, optional) – Boolean list to use as masking of the vals while adding to the map.
color (str, list, optional) – Color to use while plotting the vals. This can be a list to specify each color to use with each value.
textsize (str, optional) – Font size to draw text. labels (list, optional): Optional list of labels to place below the plotting of vals
labeltextsize (int, optional) – Size of the label text
labelcolor (str, optional) – Color to use for drawing labels
showmarker (bool, optional) – Place a marker on the map for the label
labelbuffer (int) – pixel buffer around labels, a value of 0 disables the label culling logic.
outlinecolor (color) – color to use for text outlines
zorder (int or list, optional) – zorder to use for plotting.
textoutlinewidth (int) – width of the font outline, default 3. A value <= 0 disables text outlines.
isolated (bool) – Only compute label collision against labels within this plot_values call. Default false
backgroundcolor (color) – color to use for the background of the label text, default is None.
- postprocess(**kwargs)¶
Postprocessing.
- Parameters:
filename (str) – file to save output to.
web (bool) – Write result to sys.stdout, default False.
memcache (obj) – write image to memcache
memcachekey (str) – key to use when writing to memcache.
memcacheexpire (int) – how long should we persist in memcache, default is 300.
pqstr (str) – Do pqinsert with the following LDM product name.
- scatter(lons, lats, vals, clevs, **kwargs)¶
Draw points on the map
- Parameters:
lons (list) – longitude values
lats (list) – latitude values
vals (list) – Data values for the points to use for colormapping
clevs (list) – Levels to use for ramp
**kwargs – additional options draw_colorbar (bool, optional): Draw a colorbar, default True.
- pyiem.plot.geoplot.load_bounds(filebase)¶
Load bounds file
- Parameters:
filebase (str) – the basename of the file containing the data
- Returns:
numpy 2d array of the data
pyiem.plot.layouts module¶
Standardized layouts.
- pyiem.plot.layouts.figure(logo: str = 'iem', title: str = None, subtitle: str = None, **kwargs) Figure ¶
Return an opinionated matplotlib figure.
- Parameters:
figsize (width, height) – in inches for the figure, defaults to something good for twitter.
dpi (int) – dots per inch
logo (str) – Currently, ‘iem’, ‘dep’ is supported. None disables.
title (str) – Title to place on the figure.
subtitle (str) – SubTitle to place on the figure.
apctx (dict, optional) – autoplot context.
fig (matplotlib.figure.Figure) – Figure passed in for modification for figsize only currently.
- pyiem.plot.layouts.figure_axes(logo: str = 'iem', title: str = None, subtitle: str = None, **kwargs) tuple[Figure, Axes] ¶
Return an opinionated matplotlib figure and one axes.
- Parameters:
figsize (width, height) – in inches for the figure, defaults to something good for twitter.
dpi (int) – dots per inch
logo (str) – Currently, ‘iem’, ‘dep’ is supported. None disables.
title (str) – Title to place on the figure.
subtitle (str) – SubTitle to place on the figure.
pyiem.plot.use_agg module¶
A utility to load matplotlib and set the backend to AGG
Example
from pyiem.plot.use_agg import plt
pyiem.plot.util module¶
pyiem.plot.util Plotting Utilities.
- pyiem.plot.util.centered_bins(absmax, on=0, bins=8)¶
Return a smooth binning around some number.
The returned array is +1 in size of the bins specified, since we want the bin edges.
- Parameters:
absmax (real) – positive distance from the on value for bins to enclose.
on (real) – where to center these bins.
bins (int) – number of bins to generate
Returns:
np.array
of bins
- pyiem.plot.util.draw_features_from_shapefile(gp, name, **kwargs)¶
Add features as we need to.
- pyiem.plot.util.draw_logo(fig, logoname)¶
Place the logo.
- pyiem.plot.util.fitbox(fig, text, x0, x1, y0, y1, **kwargs)¶
Fit text into a NDC box.
- Parameters:
textsize (int, optional) – First attempt this textsize to see if it fits.
- pyiem.plot.util.fontscale(ratio, fig=None)¶
Return a font size suitable for this NDC ratio.
- Parameters:
ratio (float) – value between 0 and 1
fig (matplotlib.Figure,optional) – The Figure of interest
- Returns:
float
- Return type:
font size
- pyiem.plot.util.make_panel(ndc_axbounds, fig, extent, crs, aspect, is_geoextent=False, **kwargs) GeoPanel ¶
Make a GeoPanel.
- Parameters:
ndc_axbounds (list) – the NDC coordinates of axes to create
extent (list) – x0,x1,y0,y1 in projected space plot extent, unless is_geoextent is based as True, then it is Geodetic.
crs (pyproj.CRS) – the crs of the axes
aspect (str) – matplotlib’s aspect of axes
is_geoextent (bool) – is the passed extent Geodetic?
sector_label (bool) – A Label that tracks what this is called
background (str) – background to use.
- Returns:
GeoPanel
- Return type:
the panel
- pyiem.plot.util.mask_outside_geom(gp, geom)¶
Create a white patch over the plot for what we want to ask out.
- Parameters:
gp (GeoPanel) – The GeoPanel instance
geom (geometry)
- pyiem.plot.util.mask_outside_polygon(poly_verts, gp)¶
Make outside of a polygon.
POLY_VERTS is in CCW order, as this is the interior of the polygon
- pyiem.plot.util.polygon_fill(mymap, geodf, data, **kwargs)¶
Generalize function for overlaying filled polygons on the map.
- Parameters:
mymap (MapPlot) – The MapPlot instance
geodf (GeoDataFrame) – A GeoDataFrame with a geom column.
data (dict) – The dictionary of keys and values used for picking colors
- Keyword Arguments:
ilabel (Optional[bool]) – should values be labelled? Defaults to False
lblfmt (str,optional) – format string for labels. Defaults to %s.
plotmissing (bool) – should geometries not included in the data be mapped? Defaults to True
color (str or dict) – Providing an explicit color (used for both edge and fill). Either provide one color or a dictionary to lookup a color by the mapping key.
fc (str or dict) – Same as color, but controls the fill color. Providing this value will over-ride any color setting.
ec (str or dict) – Same as color, but controls the edge color. Providing this value will over-ride any color setting.
zorder (int) – The zorder to use for this layer, default Z_FILL
lw (float) – polygon outline width
- pyiem.plot.util.pretty_bins(minval, maxval, bins=8)¶
Return a smooth binning that encloses the min and max value.
The returned array is at most the specified bins + 1 in size, but could be smaller given this algorithm and the data range.
- Parameters:
minval (real) – minimum value to enclose.
maxval (real) – maximum value to enclose.
bins (int) – maximum number of bins to generate
Returns:
np.array
of bins
- pyiem.plot.util.ramp2df(name) DataFrame ¶
Load pyIEM color ramp into a Pandas DataFrame.
- Parameters:
name (str) – the name of the bundled color ramp.
- Return type:
pandas.DataFrame
- pyiem.plot.util.sector_setter(mp, axbounds, **kwargs)¶
Use kwargs to set the MapPlot sector.
- pyiem.plot.util.update_kwargs_apctx(func)¶
Decorate things provided by an autoplot context dict.
pyiem.plot.windrose module¶
A WindrosePlot.
- class pyiem.plot.windrose.WindrosePlot(**kwargs)¶
Bases:
object
A plot that has a single windrose on it.
- barplot(direction, speed, bins, nsector, **kwargs)¶
Do the bar plotting work.
- Parameters:
cmap (colormap,optional) – Use matplotlib cmap for bars.
- draw_arrows()¶
Place arrows on the border.
- draw_logo()¶
Brand the plot.
- plot_calm()¶
Clear out the center and plot the calm value.
- pyiem.plot.windrose.histogram(speed, direction, bins, nsector)¶
Create the histogram on the given data.
- Parameters:
speed (pint.Quantity) – wind speed with units attached.
direction (pint.Quantity) – wind direction from North.
bins (pint.Quantity) – wind thresholds to use for bining. Any value below the first value is considered calm. The last value is extended to infinity to represent the last bin.
- Returns:
the percentage of reports below first bin value. dir_centers (list): the center of the direction bins. table (np.ndarray): The <direction>, <speed> histogram in percent.
- Return type:
calm_percent (float)
- pyiem.plot.windrose.plot(direction, speed, **kwargs)¶
Create a WindrosePlot, add bars and other standard things.
- Parameters:
direction (pint.Quantity) – wind direction from North.
speed (pint.Quantity) – wind speeds with units attached.
bins (pint.Quantity) – wind speed bins to produce the histogram for.
nsector (int) – The number of directional centers to divide the wind rose into. The first sector is centered on north.
rmax (float) – Hard codes the max radius value for the polar plot.
cmap (colormap) – Matplotlib colormap to use.
plot_convention (str) – Either from (default) or to.
- Returns:
WindrosePlot
Module contents¶
Plotting