Last active
February 20, 2025 09:13
-
-
Save eugen-hoppe/400e47930f733229eaf773f070c81e62 to your computer and use it in GitHub Desktop.
Histogram and Boxplot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from dataclasses import dataclass | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import matplotlib.axes as type_ax | |
| @dataclass | |
| class Plot: | |
| """src: https://gist.github.com/eugen-hoppe/400e47930f733229eaf773f070c81e62""" | |
| df: pd.DataFrame # . Cache pd.Dataframe for plot | |
| attribute: list[str] # . [ {df-column-name}, {plot-label} ] | |
| color: tuple[str, str] = ("gray", "black") # . ( color, edgecolor, ) | |
| figsize: tuple[int, int] = (10, 3) | |
| def histogram(self, bins: int = 16, ax: type_ax.Axes = None, **kwargs) -> None: | |
| if ax is None: | |
| _, ax = plt.subplots(figsize=self.figsize) | |
| ax.hist( | |
| self.df[self.attribute[0]], | |
| bins=bins, | |
| color=self.color[0], | |
| edgecolor=self.color[1], | |
| **kwargs | |
| ) | |
| ax.set_xlabel(self.attribute[1]) | |
| ax.set_ylabel("Frequency") | |
| ax.set_title(self.attribute[-1]) | |
| ax.grid(visible=False) | |
| def boxplot(self, ax: type_ax.Axes = None, **kwargs) -> None: | |
| if ax is None: | |
| _, ax = plt.subplots(figsize=self.figsize) | |
| ax.boxplot(self.df[self.attribute[0]], vert=False, **kwargs) | |
| ax.set_title("Boxplot") | |
| ax.set_ylabel(self.attribute[0]) | |
| def histogram_and_boxplot(self, bins: int = 16, bpkw: dict = {}, **kwargs) -> None: | |
| _, axes = plt.subplots(1, 2, figsize=self.figsize) | |
| self.histogram(bins, axes[0], **kwargs) | |
| self.boxplot(axes[1], **bpkw) | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment