Skip to content

Commit 72d5595

Browse files
committed
Use rc_context to save figures
This removes the gap where matplotlib is called upon outside of the context.
1 parent 77cd2e1 commit 72d5595

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

plotnine/_utils/context.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,13 @@ class plot_context:
2424
"""
2525

2626
def __init__(self, plot: ggplot, show: bool = False):
27-
self.plot = plot
28-
self.show = show
29-
30-
def __enter__(self) -> Self:
31-
"""
32-
Enclose in matplolib & pandas environments
33-
"""
3427
import matplotlib as mpl
3528

36-
self.rc_context = mpl.rc_context(self.plot.theme.rcParams)
29+
self.plot = plot
30+
self.show = show
3731

32+
# Contexts
33+
self.rc_context = mpl.rc_context(plot.theme.rcParams)
3834
# Pandas deprecated is_copy, and when we create new dataframes
3935
# from slices we do not want complaints. We always uses the
4036
# new frames knowing that they are separate from the original.
@@ -44,6 +40,11 @@ def __enter__(self) -> Self:
4440
"mode.copy_on_write",
4541
False,
4642
)
43+
44+
def __enter__(self) -> Self:
45+
"""
46+
Enclose in matplolib & pandas environments
47+
"""
4748
self.rc_context.__enter__()
4849
self.pd_option_context.__enter__()
4950
return self

plotnine/ggplot.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -672,7 +672,9 @@ def save(
672672
verbose=verbose,
673673
**kwargs,
674674
)
675-
sv.figure.savefig(**sv.kwargs)
675+
676+
with plot_context(self).rc_context:
677+
sv.figure.savefig(**sv.kwargs)
676678

677679

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

0 commit comments

Comments
 (0)