Verbeter de grootte/afstand van subplots met veel subplots in matplotlib

Zeer vergelijkbaar met deze vraagmaar met het verschil dat mijn figuur zo groot kan zijn als nodig is.

Ik moet een hele reeks verticaal gestapelde plots in matplotlib genereren. Het resultaat wordt opgeslagen met behulp van figsave en bekeken op een webpagina, dus het maakt mij niet uit hoe groot de uiteindelijke afbeelding is, zolang de subplots maar op afstand van elkaar staan zodat ze elkaar niet overlappen.

Hoe groot ik het cijfer ook toesta, de subplots lijken elkaar altijd te overlappen.

Mijn code ziet er momenteel uit als

import matplotlib.pyplot as plt
import my_other_module
titles, x_lists, y_lists = my_other_module.get_data()
fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
    plt.subplot(len(titles), 1, i)
    plt.xlabel("Some X label")
    plt.ylabel("Some Y label")
    plt.title(titles[i])
    plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)

Antwoord 1, autoriteit 100%

Probeer plt.tight_layout

te gebruiken

Als een snel voorbeeld:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"
plt.show()

Zonder strakke lay-out


Met strakke lay-out


Antwoord 2, autoriteit 73%

U kunt plt.subplots_adjustgebruiken om de afstand tussen de subplots ( bron)

Oproepnaam:

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

De parameter betekenissen (en voorgestelde standaardinstellingen) zijn:

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

De werkelijke standaardinstellingen worden bestuurd door het RC-bestand


Antwoord 3, Autoriteit 14%

Ik vond dat subplots_adjust (Hspace = 0,001) wat uiteindelijk voor mij werkt. Wanneer ik ruimte gebruik = geen, is er nog steeds witte ruimte tussen elke plot. Het instellen van het op iets heel dicht bij nul lijkt ze echter te dwingen om op te staan. Wat ik hier heb geüpload, is niet het meest elegante stuk code, maar je kunt zien hoe de Hspace werkt.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic
fig = plt.figure()
x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)
for i in range(5):
    temp = 510 + i
    ax = plt.subplot(temp)
    plt.plot(x,y)
    plt.subplots_adjust(hspace = .001)
    temp = tic.MaxNLocator(3)
    ax.yaxis.set_major_locator(temp)
    ax.set_xticklabels(())
    ax.title.set_visible(False)
plt.show()


Antwoord 4, autoriteit 10%

Vergelijkbaar met tight_layoutbiedt matplotlib nu (vanaf versie 2.2) constrained_layout. In tegenstelling tot tight_layout, dat op elk moment in de code kan worden aangeroepen voor een enkele geoptimaliseerde lay-out, is constrained_layouteen eigenschap die actief kan zijn en de lay-out voor elke stap tekenen.

Daarom moet het worden geactiveerd voor of tijdens het maken van een subplot, zoals figure(constrained_layout=True)of subplots(constrained_layout=True).

Voorbeeld:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(4,4, constrained_layout=True)
plt.show()

constrained_layout kan net zo goed worden ingesteld via rcParams

plt.rcParams['figure.constrained_layout.use'] = True

Bekijk de wat is er nieuwen de Handleiding voor beperkte lay-out


Antwoord 5, autoriteit 6%

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )

De plt.subplots_adjustmethode:

def subplots_adjust(*args, **kwargs):
    """
    call signature::
      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)
    Tune the subplot layout via the
    :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
    meanings (and suggested defaults) are::
      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for blank space between subplots
      hspace = 0.2   # the amount of height reserved for white space between subplots
    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)
    draw_if_interactive()

of

fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )

De grootte van de foto is belangrijk.

“Ik heb geprobeerd te knoeien met hspace, maar door het te vergroten lijkt het alsof alle grafieken kleiner worden zonder het overlapprobleem op te lossen.”

Om dus meer witruimte te maken en de subplotgrootte te behouden, moet de totale afbeelding groter zijn.


Antwoord 6, autoriteit 5%

Je zou de subplot_tool() kunnen proberen

plt.subplot_tool()

Other episodes