diff --git a/doc/users/whats_new/updated_figure.rst b/doc/users/whats_new/updated_figure.rst new file mode 100644 index 000000000000..881fb1192dc4 --- /dev/null +++ b/doc/users/whats_new/updated_figure.rst @@ -0,0 +1,9 @@ +Updated Figure.savefig() +------------------------ + +Added support to save the figure with the same dpi as the figure on the screen using dpi='figure' + +Example: + f = plt.figure(dpi=25) # dpi set to 25 + S = plt.scatter([1,2,3],[4,5,6]) + f.savefig('output.png', dpi='figure') # output savefig dpi set to 25 (same as figure) diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index f14c8c8c64a6..60564872870e 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1424,9 +1424,10 @@ def savefig(self, *args, **kwargs): Keyword arguments: - *dpi*: [ *None* | ``scalar > 0`` ] + *dpi*: [ *None* | ``scalar > 0`` | 'figure'] The resolution in dots per inch. If *None* it will default to - the value ``savefig.dpi`` in the matplotlibrc file. + the value ``savefig.dpi`` in the matplotlibrc file. If 'figure' + it will set the dpi to be the value of the figure. *facecolor*, *edgecolor*: the colors of the figure rectangle @@ -1473,6 +1474,8 @@ def savefig(self, *args, **kwargs): """ kwargs.setdefault('dpi', rcParams['savefig.dpi']) + if kwargs['dpi'] == 'figure': + kwargs['dpi'] = self.get_dpi() frameon = kwargs.pop('frameon', rcParams['savefig.frameon']) transparent = kwargs.pop('transparent', rcParams['savefig.transparent']) diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index 1fdf121b32d8..df2642ab8ac2 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -117,6 +117,15 @@ def validate_float_or_None(s): except ValueError: raise ValueError('Could not convert "%s" to float' % s) +def validate_dpi(s): + """confirm s is string 'figure' or convert s to float or raise""" + if s == 'figure': + return s + try: + return float(s) + except ValueError: + raise ValueError('"%s" is not string "figure" or' + ' could not convert "%s" to float' % (s, s)) def validate_int(s): """convert s to int or raise""" @@ -749,7 +758,7 @@ def __call__(self, s): closedmax=False)], ## Saving figure's properties - 'savefig.dpi': [100, validate_float], # DPI + 'savefig.dpi': [100, validate_dpi], # DPI 'savefig.facecolor': ['w', validate_color], # facecolor; white 'savefig.edgecolor': ['w', validate_color], # edgecolor; white 'savefig.frameon': [True, validate_bool],