Skip to content

Commit

Permalink
fix(boxplot): support seaborn axes flip (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
SaaiVenkat authored Jun 25, 2024
1 parent f04d791 commit 023907f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
7 changes: 7 additions & 0 deletions maidr/core/plot/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

class BoxPlotContainer(DictMergerMixin):
def __init__(self):
self._orientation = None
self.boxes = []
self.medians = []
self.whiskers = []
Expand All @@ -23,6 +24,12 @@ def __init__(self):
def __repr__(self):
return f"<BoxPlotContainer object with {len(self.boxes)} boxes>"

def orientation(self):
return self._orientation

def set_orientation(self, orientation: str):
self._orientation = orientation

def add_artists(self, artist: dict):
for box in artist["boxes"]:
self.boxes.append(box)
Expand Down
41 changes: 40 additions & 1 deletion maidr/patch/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ def get_bxp_context(cls) -> BoxPlotContainer:
def add_bxp_context(cls, bxp_context: dict) -> None:
cls.get_bxp_context().add_artists(bxp_context)

@classmethod
def set_bxp_orientation(cls, orientation: str) -> None:
cls.get_bxp_context().set_orientation(orientation)


@wrapt.patch_function_wrapper(Axes, "bxp")
def mpl_box(wrapped, _, args, kwargs) -> dict:
Expand Down Expand Up @@ -68,10 +72,45 @@ def sns_box(wrapped, _, args, kwargs) -> Axes:

# Extract the boxplot data points for MAIDR from the plot.
ax = FigureManager.get_axes(bxp_container.bxp_stats())
orientation = "horz" if kwargs.get("orient", "v") == "h" else "vert"
orientation = (
"horz"
if bxp_container.orientation() == "y" or bxp_container.orientation() == "h"
else "vert"
)
FigureManager.create_maidr(
ax, PlotType.BOX, bxp_stats=bxp_container.bxp_stats(), orientation=orientation
)

# Return to the caller.
return plot


def sns_infer_new_orient(wrapped, instance, args, kwargs) -> str:
if BoxplotContextManager.is_internal_context():
orientation = instance.orient
BoxplotContextManager.set_bxp_orientation(orientation)

return wrapped(*args, **kwargs)


def patch_seaborn():
import packaging.version as version
import seaborn

sns_version = seaborn.__version__
min_version = "0.12"

if version.parse(sns_version) < version.parse(min_version):
wrapt.wrap_function_wrapper(
"seaborn.categorical", "_BoxPlotter.plot", sns_version
)
else:
wrapt.wrap_function_wrapper(
"seaborn.categorical",
"_CategoricalPlotter.plot_boxes",
sns_infer_new_orient,
)


# Apply the appropriate patches based on the Seaborn version
patch_seaborn()

0 comments on commit 023907f

Please sign in to comment.