Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

plot histogram with class bins #216

Merged
merged 14 commits into from
Jul 3, 2024
62 changes: 62 additions & 0 deletions mapclassify/classifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,68 @@ def plot(
plt.savefig(file_name, dpi=dpi)
return f, ax

def plot_histogram(
self,
hist_color="dodgerblue",
martinfleis marked this conversation as resolved.
Show resolved Hide resolved
linecolor="black",
ax=None,
despine=True,
hist_kwargs=None,
martinfleis marked this conversation as resolved.
Show resolved Hide resolved
):
"""Plot histogram of `y` with bin values superimposed

Parameters
----------
hist_color : str, optional
hue to color bars of the histogram, by default "dodgerblue". This option
overrides the 'color' entry in `hist_kwargs` if specified.
linecolor : str, optional
color of the lines demarcating each class bin, by default "black"
ax : matplotlib.Axes, optional
axes object to plot onto, by default None
despine : bool, optional
If True, to use seaborn's despine function to remove top and right axes,
default is True
hist_kwargs : dict, optional
additional keyword arguments passed to pandas.Series.histogram, by default
None

Returns
-------
matplotlib.Axes
an Axes object with histogram and class bins

Raises
------
ImportError
depends matplotlib and rasies if not installed
"""
try:
import matplotlib.pyplot as plt
if ax is None:
_, ax = plt.subplots()
except ImportError as e:
raise ImportError from e(
"You must have matplotlib available to use this function"
)
if hist_kwargs is None:
hist_kwargs = dict()
# override color in case specified explicitly and inside the dict
if "color" not in hist_kwargs:
hist_kwargs["color"] = hist_color
# plot `y` as a histogram
ax.hist(self.y, **hist_kwargs)
# get the top of the ax so we know how high to raise each class bar
lim = ax.get_ylim()[1]
# plot upper limit of each bin
for i in self.bins:
ax.vlines(i, 0, lim, color=linecolor)
# despine if specified
if despine:
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
return ax


class HeadTailBreaks(MapClassifier):
"""
Expand Down
Loading