vibespatial.api.plotting¶
Classes¶
Make plots of Series or DataFrame. |
Functions¶
|
Plot a GeoSeries. |
|
Plot a GeoDataFrame. |
Module Contents¶
- vibespatial.api.plotting.plot_series(s: vibespatial.api.GeoSeries, cmap: str | matplotlib.colors.Colormap | None = None, color: str | collections.abc.Sequence | None = None, ax: matplotlib.axes.Axes | None = None, figsize: tuple[float, float] | None = None, aspect: float | Literal['auto', 'equal', None] = 'auto', autolim: bool = True, **style_kwds) matplotlib.axes.Axes¶
Plot a GeoSeries.
Generate a plot of a GeoSeries geometry with matplotlib.
Parameters¶
- sSeries
The GeoSeries to be plotted. Currently Polygon, MultiPolygon, LineString, MultiLineString, Point and MultiPoint geometries can be plotted.
- cmapstr (default None)
The name of a colormap recognized by matplotlib. Any colormap will work, but categorical colormaps are generally recommended. Examples of useful discrete colormaps include:
tab10, tab20, Accent, Dark2, Paired, Pastel1, Set1, Set2
- colorstr, np.array, pd.Series, List (default None)
If specified, all objects will be colored uniformly.
- axmatplotlib.pyplot.Artist (default None)
axes on which to draw the plot
- figsizepair of floats (default None)
Size of the resulting matplotlib.figure.Figure. If the argument ax is given explicitly, figsize is ignored.
- aspect‘auto’, ‘equal’, None or float (default ‘auto’)
Set aspect of axis. If ‘auto’, the default aspect for map plots is ‘equal’; if however data are not projected (coordinates are long/lat), the aspect is by default set to 1/cos(s_y * pi/180) with s_y the y coordinate of the middle of the GeoSeries (the mean of the y range of bounding box) so that a long/lat square appears square in the middle of the plot. This implies an Equirectangular projection. If None, the aspect of ax won’t be changed. It can also be set manually (float) as the ratio of y-unit to x-unit.
- autolimbool (default True)
Update axes data limits to contain the new geometries.
- **style_kwdsdict
Color options to be passed on to the actual plot function, such as
edgecolor,facecolor,linewidth,markersize,alpha.
Returns¶
ax : matplotlib axes instance
- vibespatial.api.plotting.plot_dataframe(df: vibespatial.api.GeoDataFrame, column: str | numpy.ndarray | pandas.Series | pandas.Index | None = None, cmap: str | matplotlib.colors.Colormap | dict | None = None, color: str | collections.abc.Sequence | None = None, ax: matplotlib.axes.Axes | None = None, cax: matplotlib.axes.Axes | None = None, categorical: bool = False, legend: bool = False, scheme: str | None = None, k: int = 5, vmin: float | None = None, vmax: float | None = None, markersize: str | float | collections.abc.Sequence | dict | None = None, figsize: tuple[float, float] | None = None, legend_kwds: dict | None = None, categories: collections.abc.Sequence | None = None, classification_kwds: dict | None = None, missing_kwds: dict | None = None, aspect: float | Literal['auto', 'equal', None] = 'auto', autolim: bool = True, **style_kwds) matplotlib.axes.Axes¶
Plot a GeoDataFrame.
Generate a plot of a GeoDataFrame with matplotlib. If a column is specified, the plot coloring will be based on values in that column.
Parameters¶
- column
str,np.array,pd.Series,pd.Index(defaultNone) The name of the GeoDataFrame column,
np.array,pd.Series, orpd.Indexto be plotted. Ifnp.array,pd.Series, orpd.Indexare used then it must have same length as GeoDataFrame. Values are used to color the plot. Ignored ifcoloris also set.- kind: str
The kind of plots to produce. The default is to create a map (
"geo"). Other supported kinds of plots from pandas:'line': line plot'bar': vertical bar plot'barh': horizontal bar plot'hist': histogram'box': BoxPlot'kde': Kernel Density Estimation plot'density': same as'kde''area': area plot'pie': pie plot'scatter': scatter plot'hexbin': hexbin plot.
- cmap
str|Colormap|dict(defaultNone) The name of a colormap recognized by matplotlib, a
matplotlib.colors.Colormapor a dictionary ofvalue: colormapping for categorical plots.- color
str,np.array,pd.Series(defaultNone) Color of the geometry. If specified as scalar matplotlib understands as a color (
str,tupleor RGBA etc.), all objects will be colored uniformly. If specifies as array-like of the same length as GeoDataFrame, individual colors will be mapped to respective geometries.- ax
matplotlib.axes.Axes(defaultNone) matplotlib.axes.Axesaxes on which to draw the plot- cax
matplotlib.axes.Axes(defaultNone) matplotlib.axes.Axeson which to draw the legend in case of a colorbar.- categorical
bool(defaultFalse) Determine whether values of
columnshall be treated as a categorical variable or as a continuous one. For non-numerical columns, this will be set toTrueautomatically.- legend
bool(defaultFalse) Plot a legend. Ignored if no
columnis given, or ifcoloris given. This can be amatplotlib.legend.Legendin case of categorical variables or those with setschemeand a categorical legend, or a :class`:matplotlib.colorbar.Colorbar` in case of continuous variables or those with setschemeand a colorbar legend.- schemestr (default None)
Name of a choropleth classification scheme (requires
mapclassify). Amapclassify.classifiers.MapClassifierobject will be used under the hood. Supported are all schemes provided bymapclassify(e.g.'BoxPlot','EqualInterval','FisherJenks','FisherJenksSampled','HeadTailBreaks','JenksCaspall','JenksCaspallForced','JenksCaspallSampled','MaxP','MaximumBreaks','NaturalBreaks','Quantiles','Percentiles','StdMean','UserDefined'). Arguments can be passed inclassification_kwds.This requires continuous variable and can result in a categorical plot where each classification bin is mapped to a category (default behavior) or in a continuous plot where bins are used to define
matplotlib.colors.BoundaryNorm. The latter can be enabled by specifyingcolorbar=Truewithinlegend_kwdsand yields colorbar legend.- k
int(default5) Number of classes (ignored if
schemeisNone)- vmin
Noneorfloat(defaultNone) Minimum value of
cmaporscheme. IfNone, the minimum data value in the column to be plotted is used.- vmax
Noneorfloat(defaultNone) Maximum value of
cmaporscheme. IfNone, the maximum data value in the column to be plotted is used.- markersize
strorfloatorSequence(default None) Only applies to point geometries within a GeoDataFrame. If a
str, will use the values in the column of the GeoDataFrame specified bymarkersizeto set the size of markers. Otherwise can be a value to apply to all points, or a sequence of the same length as the number of points.- figsize
tupleof integers (default None) Size of the resulting
matplotlib.figure.Figure. If the argumentaxis given explicitly,figsizeis ignored.- legend_kwdsdict (default None)
Keyword arguments to pass to
matplotlib.pyplot.legend()(e.g.labels, orframeon) ormatplotlib.pyplot.colorbar()(e.g.orientation). Additional accepted keywords whenschemeis specified:fmtstringA formatting specification for the bin edges of the classes in the legend. For example, to have no decimals:
{"fmt": "{:.0f}"}.intervalboolean (default False)An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend.
colorbarboolean (default False)An option to control whether the legend should be treated as categorical or as a colorbar. When set to True,
fmtandintervalshall not be used.
- categories
list-like Ordered list-like object of categories to be used for categorical plot.
- classification_kwds
dict(defaultNone) Keyword arguments to pass to
mapclassifywhenschemeis set.- missing_kwds
dict(default None) Keyword arguments specifying style options (e.g. color, hatch, linewidth) to be passed on to geometries with missing values in addition to or overwriting other
style_kwds. IfNone, geometries with missing values are not plotted.- aspect‘auto’, ‘equal’,
Noneorfloat(default'auto') Set aspect of axis. If
'auto', the default aspect for map plots is'equal'; if however data are not projected (coordinates are long/lat), the aspect is by default set to1/cos(df_y * pi/180)withdf_ythe y coordinate of the middle of the GeoDataFrame (the mean of the y range of bounding box) so that a long/lat square appears square in the middle of the plot. This implies an Equirectangular projection. IfNone, the aspect ofaxwon’t be changed. It can also be set manually (float) as the ratio of y-unit to x-unit.- autolim
bool(defaultTrue) Update axes data limits to contain the new geometries.
- **style_kwdsdict
Style options to be passed on to the actual plot function, such as
edgecolor,facecolor,linewidth,markersize,alpha. These can be scalar, which are uniformly mapped to all geometries, array-likes of the same length as GeoDataFrame, which are mapped to their respective geometries, or dictionaries mapping styles to values when dealing with categorical plots.
Returns¶
ax : matplotlib axes instance
Examples¶
>>> import geodatasets >>> df = geopandas.read_file(geodatasets.get_path("nybb")) >>> df.head() BoroCode ... geometry 0 5 ... MULTIPOLYGON (((970217.022 145643.332, 970227.... 1 4 ... MULTIPOLYGON (((1029606.077 156073.814, 102957... 2 3 ... MULTIPOLYGON (((1021176.479 151374.797, 102100... 3 1 ... MULTIPOLYGON (((981219.056 188655.316, 980940.... 4 2 ... MULTIPOLYGON (((1012821.806 229228.265, 101278...
>>> df.plot("BoroName", cmap="Set1")
See the User Guide page ../../user_guide/mapping for details.
- column
- class vibespatial.api.plotting.GeoplotAccessor(data: pandas.Series | pandas.DataFrame)¶
Make plots of Series or DataFrame.
Uses the backend specified by the option
plotting.backend. By default, matplotlib is used.Parameters¶
- dataSeries or DataFrame
The object for which the method is called.
Attributes¶
- xlabel or position, default None
Only used if data is a DataFrame.
- ylabel, position or list of label, positions, default None
Allows plotting of one column versus another. Only used if data is a DataFrame.
- kindstr
The kind of plot to produce:
‘line’ : line plot (default)
‘bar’ : vertical bar plot
‘barh’ : horizontal bar plot
‘hist’ : histogram
‘box’ : boxplot
‘kde’ : Kernel Density Estimation plot
‘density’ : same as ‘kde’
‘area’ : area plot
‘pie’ : pie plot
‘scatter’ : scatter plot (DataFrame only)
‘hexbin’ : hexbin plot (DataFrame only)
- axmatplotlib axes object, default None
An axes of the current figure.
- subplotsbool or sequence of iterables, default False
Whether to group columns into subplots:
False: No subplots will be usedTrue: Make separate subplots for each column.sequence of iterables of column labels: Create a subplot for each group of columns. For example [(‘a’, ‘c’), (‘b’, ‘d’)] will create 2 subplots: one with columns ‘a’ and ‘c’, and one with columns ‘b’ and ‘d’. Remaining columns that aren’t specified will be plotted in additional subplots (one per column).
- sharexbool, default True if ax is None else False
In case
subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax andsharex=Truewill alter all x axis labels for all axis in a figure.- shareybool, default False
In case
subplots=True, share y axis and set some y axis labels to invisible.- layouttuple, optional
(rows, columns) for the layout of subplots.
- figsizea tuple (width, height) in inches
Size of a figure object.
- use_indexbool, default True
Use index as ticks for x axis.
- titlestr or list
Title to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and subplots is True, print each item in the list above the corresponding subplot.
- gridbool, default None (matlab style default)
Axis grid lines.
- legendbool or {‘reverse’}
Place legend on axis subplots.
- stylelist or dict
The matplotlib line style per column.
- logxbool or ‘sym’, default False
Use log scaling or symlog scaling on x axis.
- logybool or ‘sym’ default False
Use log scaling or symlog scaling on y axis.
- loglogbool or ‘sym’, default False
Use log scaling or symlog scaling on both x and y axes.
- xtickssequence
Values to use for the xticks.
- ytickssequence
Values to use for the yticks.
- xlim2-tuple/list
Set the x limits of the current axes.
- ylim2-tuple/list
Set the y limits of the current axes.
- xlabellabel, optional
Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the x-column name for planar plots.
Changed in version 2.0.0: Now applicable to histograms.
- ylabellabel, optional
Name to use for the ylabel on y-axis. Default will show no ylabel, or the y-column name for planar plots.
Changed in version 2.0.0: Now applicable to histograms.
- rotfloat, default None
Rotation for ticks (xticks for vertical, yticks for horizontal plots).
- fontsizefloat, default None
Font size for xticks and yticks.
- colormapstr or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that name from matplotlib.
- colorbarbool, optional
If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots).
- positionfloat
Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center).
- tablebool, Series or DataFrame, default False
If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table.
- yerrDataFrame, Series, array-like, dict and str
See Plotting with Error Bars for detail.
- xerrDataFrame, Series, array-like, dict and str
Equivalent to yerr.
- stackedbool, default False in line and bar plots, and True in area plot
If True, create stacked plot.
- secondary_ybool or sequence, default False
Whether to plot on the secondary y-axis if a list/tuple, which columns to plot on secondary y-axis.
- mark_rightbool, default True
When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend.
- include_boolbool, default is False
If True, boolean values can be plotted.
- backendstr, default None
Backend to use instead of the backend specified in the option
plotting.backend. For instance, ‘matplotlib’. Alternatively, to specify theplotting.backendfor the whole session, setpd.options.plotting.backend.- **kwargs
Options to pass to matplotlib plotting method.
Returns¶
matplotlib.axes.Axesor numpy.ndarray of themIf the backend is not the default matplotlib one, the return value will be the object returned by the backend.
See Also¶
matplotlib.pyplot.plot : Plot y versus x as lines and/or markers. DataFrame.hist : Make a histogram. DataFrame.boxplot : Make a box plot. DataFrame.plot.scatter : Make a scatter plot with varying marker
point size and color.
- DataFrame.plot.hexbinMake a hexagonal binning plot of
two variables.
- DataFrame.plot.kdeMake Kernel Density Estimate plot using
Gaussian kernels.
DataFrame.plot.area : Make a stacked area plot. DataFrame.plot.bar : Make a bar plot. DataFrame.plot.barh : Make a horizontal bar plot.
Notes¶
See matplotlib documentation online for more on this subject
If kind = ‘bar’ or ‘barh’, you can specify relative alignments for bar plot layout by position keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
Examples¶
For Series:
For DataFrame:
For SeriesGroupBy:
For DataFrameGroupBy:
- geo(*args, **kwargs)¶