Ich muss zwei Unterplattformen zu einer Figur hinzufügen. Ein Subplot muss etwa dreimal so breit sein wie der zweite (gleiche Höhe). Ich erreichte dies unter Verwendung GridSpec
und der colspan
Argument, aber ich möchte dies mit figure
tun, damit ich in PDF speichern kann. Ich kann die erste Zahl mit dem Argument figsize
im Konstruktor anpassen, aber wie ändere ich die Größe des zweiten Plots?Matplotlib unterschiedliche Größe Nebenplots
Antwort
Sie gridspec
verwenden können und figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
I verwendet pyplot
‚s axes
Objekt manuell die Größen einstellen, ohne GridSpec
mit:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02
rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]
fig = plt.figure()
cones = plt.axes(rect_cones)
box = plt.axes(rect_box)
cones.plot(x, y)
box.plot(y, x)
plt.show()
Wahrscheinlich der einfachste Weg, verwendet subplot2grid
, beschrieben i n Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
gleich
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so BMU Beispiel wird:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
Eine andere Möglichkeit ist es, die subplots
Funktion zu verwenden, und das Breitenverhältnis mit gridspec_kw
passieren:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
f, (a0, a1) = plt.subplots(1,2, gridspec_kw = {'width_ratios':[3, 1]})
a0.plot(x,y)
a1.plot(y,x)
f.tight_layout()
f.savefig('grid_figure.pdf')
Eigentlich mag ich diese Option am meisten, ich bin froh, dass ich bis zum Ende scrollte :) – astrojuanlu
Danke dafür; Die Art und Weise, wie Dinge getan werden, ist viel sauberer imo. –
Ich mag Subplots besser als gridspec, da Sie sich nicht mehr mit Einstellungen in der Liste für die Achse beschäftigen müssen (mit gridspec müssen Sie noch die Achse und die Plots eins nach dem anderen machen). Subplots sind also sauberer und schneller zu benutzen –
Gridspec funktioniert mit einer normalen Figur. – tillsten