Verbessern Sie die Größe/den Abstand der Nebenhandlungen mit vielen Nebenhandlungen

Lesezeit: 5 Minuten

Benutzeravatar von mcstrother
Mcstrother

Ich muss eine ganze Reihe vertikal gestapelter Diagramme in Matplotlib generieren. Das Ergebnis wird mit gespeichert savefig und auf einer Webseite angezeigt werden, also ist es mir egal, wie groß das endgültige Bild ist, solange die Nebenhandlungen so beabstandet sind, dass sie sich nicht überlappen.

Egal wie groß ich die Figur lasse, die Nebenhandlungen scheinen sich immer zu überschneiden.

Mein Code sieht derzeit so aus

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)

  • Diese Frage gilt auch für pandas.DataFrame.plot mit Subplots und auf Seaborn-Plots auf Axtebene (die mit dem Axtparameter): sns.lineplot(..., ax=ax)

    – Trenton McKinney

    2. Mai um 17:34 Uhr

Benutzeravatar von Joe Kington
Joe Kington

Lesen Sie bitte matplotlib: Enge Layout-Anleitung und versuchen Sie es mit matplotlib.pyplot.tight_layoutoder matplotlib.figure.Figure.tight_layout

Als kurzes Beispiel:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Ohne straffes Layout

Geben Sie hier die Bildbeschreibung ein


Mit straffem Layout

Geben Sie hier die Bildbeschreibung ein

Benutzeravatar von CyanRook
CyanRook

Sie können verwenden plt.subplots_adjust um den Abstand zwischen den Nebenhandlungen zu ändern.

Rufsignatur:

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

Die Parameterbedeutungen (und vorgeschlagenen Standardwerte) sind:

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

Die eigentlichen Standardwerte werden von der rc-Datei gesteuert

Benutzeravatar von Alexa Halford
Alexa Halford

Verwenden subplots_adjust(hspace=0) oder eine sehr kleine Zahl (hspace=0.001) wird den Leerraum zwischen den Subplots vollständig entfernen, wohingegen hspace=None nicht.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic

fig = plt.figure(figsize=(8, 8))

x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)

for i in range(1, 6):
    temp = 510 + i
    ax = plt.subplot(temp)
    plt.plot(x, y)
    plt.subplots_adjust(hspace=0)
    temp = tic.MaxNLocator(3)
    ax.yaxis.set_major_locator(temp)
    ax.set_xticklabels(())
    ax.title.set_visible(False)

plt.show()

hspace=0 oder hspace=0.001

Geben Sie hier die Bildbeschreibung ein

hspace=None

Geben Sie hier die Bildbeschreibung ein

ImportanceOfBeingErnests Benutzeravatar
ImportanceOfBeingErnest

Ähnlich zu tight_layout matplotlib jetzt (ab Version 2.2) zur Verfügung stellt constrained_layout. Im Kontrast zu tight_layoutdie jederzeit im Code für ein einzelnes optimiertes Layout aufgerufen werden kann, constrained_layout ist eine Eigenschaft, die aktiv sein kann und das Layout vor jedem Zeichenschritt optimiert.

Daher muss es vor oder während der Erstellung von Nebenhandlungen aktiviert werden, z figure(constrained_layout=True) oder subplots(constrained_layout=True).

Beispiel:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(4,4, constrained_layout=True)

plt.show()

Geben Sie hier die Bildbeschreibung ein

constrained_layout kann auch über gesetzt werden rcParams

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

Siehe die Was ist der neue Eintrag und die Leitfaden für eingeschränktes Layout

Der Benutzeravatar des Demz
Der Demz

import matplotlib.pyplot as plt

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

Das plt.subplots_adjust Methode:

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()

oder

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

Die Größe des Bildes spielt eine Rolle.

“Ich habe versucht, mit hspace herumzuspielen, aber das Erhöhen scheint nur alle Diagramme kleiner zu machen, ohne das Überlappungsproblem zu lösen.”

Um also mehr Leerraum zu schaffen und die Unterplotgröße beizubehalten, muss das Gesamtbild größer sein.

Benutzeravatar von Trenton McKinney
Trenton McKinney

Du könntest es versuchen .subplot_tool()

plt.subplot_tool()

  • Behebung dieses Problems beim Plotten eines Datenrahmens mit pandas.DataFrame.plotdie verwendet matplotlib als Standard-Backend.
    • Das Folgende funktioniert für was auch immer kind= angegeben ist (zB 'bar', 'scatter', 'hist'etc.).
  • Getestet in python 3.8.12, pandas 1.3.4, matplotlib 3.4.3

Importe und Beispieldaten

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# sinusoidal sample data
sample_length = range(1, 15+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name="radians"), columns=[f'freq: {i}x' for i in sample_length])

# default plot with subplots; each column is a subplot
axes = df.plot(subplots=True)

Geben Sie hier die Bildbeschreibung ein

Passen Sie den Abstand an

  • Passen Sie die Standardparameter in an pandas.DataFrame.plot
    1. Veränderung figsize: Eine Breite von 5 und eine Höhe von 4 für jede Nebenhandlung ist ein guter Ausgangspunkt.
    2. Veränderung layout: (Zeilen, Spalten) für die Anordnung von Nebengrundstücken.
    3. sharey=True und sharex=True Daher wird nicht auf jedem Nebenplot Platz für redundante Beschriftungen benötigt.
  • Das .plot -Methode gibt ein numpy-Array von zurück matplotlib.axes.Axesdie abgeflacht sein sollte, um leicht damit arbeiten zu können.
  • Verwenden .get_figure() die zu extrahieren DataFrame.plot Figurenobjekt aus einem der Axes.
  • Verwenden fig.tight_layout() wenn gewünscht.
axes = df.plot(subplots=True, layout=(3, 5), figsize=(25, 16), sharex=True, sharey=True)

# flatten the axes array to easily access any subplot
axes = axes.flat

# extract the figure object
fig = axes[0].get_figure()

# use tight_layout
fig.tight_layout()

Geben Sie hier die Bildbeschreibung ein

df

# display(df.head(3))
         freq: 1x  freq: 2x  freq: 3x  freq: 4x  freq: 5x  freq: 6x  freq: 7x  freq: 8x  freq: 9x  freq: 10x  freq: 11x  freq: 12x  freq: 13x  freq: 14x  freq: 15x
radians                                                                                                                                                            
0.00     0.000000  0.000000  0.000000  0.000000  0.000000  0.000000  0.000000  0.000000  0.000000   0.000000   0.000000   0.000000   0.000000   0.000000   0.000000
0.01     0.010000  0.019999  0.029996  0.039989  0.049979  0.059964  0.069943  0.079915  0.089879   0.099833   0.109778   0.119712   0.129634   0.139543   0.149438
0.02     0.019999  0.039989  0.059964  0.079915  0.099833  0.119712  0.139543  0.159318  0.179030   0.198669   0.218230   0.237703   0.257081   0.276356   0.295520

1399680cookie-checkVerbessern Sie die Größe/den Abstand der Nebenhandlungen mit vielen Nebenhandlungen

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy