Verbessern Sie die Größe/den Abstand der Nebenhandlungen mit vielen Nebenhandlungen
Lesezeit: 5 Minuten
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)
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
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
hspace=None
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()
constrained_layout kann auch über gesetzt werden rcParams
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()
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)
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