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

feat: support seaborn bar and count plot #12

Merged
merged 14 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ cython_debug/

# Vscode config files
# .vscode/
.vscode/launch.json

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@
let maidr = {
"type": "bar",
"title": "The Number of Tips by Day",
"selector": "TODO: Enter your bar plot selector here",
"selector": "path[clip-path='url(#p6c5d07f9e0)']",
"axes": {
"x": {
"label": "Day",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def plot():
def main():
bar_plot = plot()
bar_maidr = maidr.bar(bar_plot)
bar_maidr.save(get_filepath("example_bar_plot.html"))
bar_maidr.save(get_filepath("example_mpl_bar_plot.html"))


if __name__ == "__main__":
Expand Down
397 changes: 397 additions & 0 deletions example/bar/seaborn/example_sns_bar_plot.html

Large diffs are not rendered by default.

38 changes: 38 additions & 0 deletions example/bar/seaborn/example_sns_bar_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os

import matplotlib.pyplot as plt
import maidr
import seaborn as sns


def get_filepath(filename: str) -> str:
current_file_path = os.path.abspath(__file__)
directory = os.path.dirname(current_file_path)
return os.path.join(directory, filename)


def plot():
# Load the penguins dataset
penguins = sns.load_dataset("penguins")

# Create a bar plot showing the average body mass of penguins by species
plt.figure(figsize=(10, 6))
b_plot = sns.barplot(
x="species", y="body_mass_g", data=penguins, errorbar="sd", palette="Blues_d"
)
b_plot.bar
plt.title("Average Body Mass of Penguins by Species")
plt.xlabel("Species")
plt.ylabel("Body Mass (g)")

return b_plot


def main():
bar_plot = plot()
bar_maidr = maidr.bar(bar_plot)
bar_maidr.save(get_filepath("example_sns_bar_plot.html"))


if __name__ == "__main__":
main()
33 changes: 23 additions & 10 deletions maidr/core/plot/bar_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,31 @@ def __extract_level(self) -> list | None:
def __extract_data(self) -> list | None:
plot = self.plot

if isinstance(plot, BarContainer) and isinstance(plot.datavalues, Iterable):
bc_data = []
for value in plot.datavalues:
if isinstance(value, np.integer):
bc_data.append(int(value))
elif isinstance(value, np.floating):
bc_data.append(float(value))
else:
bc_data.append(value)
data = bc_data
if isinstance(plot, Axes):
plot = self.__extract_bar_container(plot)
if isinstance(plot, BarContainer):
data = self.__extract_bar_container_data(plot)
else:
# TODO: What would be the right exception? ExtractionError?
raise TypeError("")

return data

def __extract_bar_container_data(self, plot: BarContainer) -> list | None:
if not isinstance(plot.datavalues, Iterable):
return None

data = []
for value in plot.datavalues:
if isinstance(value, np.integer):
data.append(int(value))
elif isinstance(value, np.floating):
data.append(float(value))
else:
data.append(value)
return data

def __extract_bar_container(self, plot: Axes) -> BarContainer | None:
for container in plot.containers:
if isinstance(container, BarContainer):
return container
3 changes: 2 additions & 1 deletion maidr/maidr.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from __future__ import annotations

from matplotlib.axes import Axes
from matplotlib.container import BarContainer

from .core.maidr import Maidr
from .core.enum.plot_type import PlotType
from .utils.figure_manager import FigureManager


def bar(plot: BarContainer) -> Maidr:
def bar(plot: Axes | BarContainer) -> Maidr:
fig = FigureManager.get_figure(plot)
plot_type = [PlotType.BAR for _ in fig.axes] if fig and fig.axes else []
return FigureManager.create_maidr(fig, plot, plot_type)
Expand Down
11 changes: 8 additions & 3 deletions maidr/utils/figure_manager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations
from matplotlib.axes import Axes

from matplotlib.container import BarContainer
from matplotlib.figure import Figure
Expand Down Expand Up @@ -35,13 +36,17 @@ def create_maidr(
return Maidr(fig, maidr_data)

@staticmethod
def get_figure(artist: BarContainer | None) -> Figure | None:
def get_figure(artist: Axes | BarContainer | None) -> Figure | None:
if not artist:
return None

fig = None
# bar container - get figure from the first occurrence of any artist
if isinstance(artist, BarContainer):
# axes - get figure from the the artist
if isinstance(artist, Axes):
fig = artist.get_figure()

# bar container - get figure from the first occurrence of any child artist
elif isinstance(artist, BarContainer):
fig = next(
(
child_artist.get_figure()
Expand Down
Loading