pythonmatplotlib

Get the DPI for a PyPlot figure


At least in Spyder, the PyPlot plots can be low resolution, e.g., from:

import numpy as np
import matplotlib.pyplot as plt
# import seaborn as sns
rng = np.random.default_rng(1)
scat = plt.scatter( *rng.integers( 10, size=(2,10) ) )

My web surfing has brought me to a suggested solution: Increase the dots-per-inch.

plt.rcParams['figure.dpi']=300

Surfing indicates that the default is 100.

After much experimentation, is there a way to "get" the DPI from the plotted object, e.g., scat above? There doesn't seem to be a scat.dpi, scat.getdpi, or scat.get_dpi.

Afternote: Thanks to BigBen for pointing out the object-oriented interface. It requires the definition of a figure and axes therein before actually plotting the data. His code patterns seem to return a DPI, but in Spyder, the displayed figure isn't updated with the plotted data.

enter image description here

Web surfing yields indications that "inline" plots in Spyder are static. I'm wasn't entirely sure if this was the cause, since the plots in the "Plots" window aren't inline (top half of above image), but they also fail to show the plotted data. Eventually, I found that setting the following did allow BigBen's solution to work: Tools -> Preferences -> IPython console -> Graphics -> Graphics backend -> Automatic. A separate window opens for the figure and axes when it is defined by the source code, and it is updated with plot of the data when scatter is invoked.


Solution

  • There doesn't seem to be a scat.dpi, scat.getdpi, or scat.get_dpi.

    This makes sense, because scatter returns a PathCollection.

    The relevant property and method are Figure.dpi or Figure.get_dpi. Highly suggest you use the object-oriented interface:

    fig, ax = plt.subplots()
    ax.scatter(*rng.integers(10, size=(2,10)))
    print(fig.dpi) # returns 100.0
    

    Using the pyplot interface:

    plt.gcf().dpi
    

    or

    plt.gcf().get_dpi()