Skip to content

Commit

Permalink
Use rc_context to save figures
Browse files Browse the repository at this point in the history
This removes the gap where matplotlib is called upon outside of the
context.
  • Loading branch information
has2k1 committed Apr 25, 2024
1 parent 77cd2e1 commit 72d5595
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
17 changes: 9 additions & 8 deletions plotnine/_utils/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,13 @@ class plot_context:
"""

def __init__(self, plot: ggplot, show: bool = False):
self.plot = plot
self.show = show

def __enter__(self) -> Self:
"""
Enclose in matplolib & pandas environments
"""
import matplotlib as mpl

self.rc_context = mpl.rc_context(self.plot.theme.rcParams)
self.plot = plot
self.show = show

# Contexts
self.rc_context = mpl.rc_context(plot.theme.rcParams)
# Pandas deprecated is_copy, and when we create new dataframes
# from slices we do not want complaints. We always uses the
# new frames knowing that they are separate from the original.
Expand All @@ -44,6 +40,11 @@ def __enter__(self) -> Self:
"mode.copy_on_write",
False,
)

def __enter__(self) -> Self:
"""
Enclose in matplolib & pandas environments
"""
self.rc_context.__enter__()
self.pd_option_context.__enter__()
return self
Expand Down
9 changes: 6 additions & 3 deletions plotnine/ggplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,9 @@ def save(
verbose=verbose,
**kwargs,
)
sv.figure.savefig(**sv.kwargs)

with plot_context(self).rc_context:
sv.figure.savefig(**sv.kwargs)


ggsave = ggplot.save
Expand Down Expand Up @@ -780,5 +782,6 @@ def facet_pages(column)
# Re-add the first element to the iterator, if it was removed
for plot in plots:
fig = plot.draw()
# Save as a page in the PDF file
pdf.savefig(fig, **fig_kwargs)
with plot_context(plot).rc_context:
# Save as a page in the PDF file
pdf.savefig(fig, **fig_kwargs)

0 comments on commit 72d5595

Please sign in to comment.