python - Matplotlib: Constrain plot width while allowing flexible height -
what achive plots equal scale aspect ratio, , fixed width, dynamically chosen height.
to make more concrete, consider following plotting example:
import matplotlib mpl import matplotlib.pyplot plt def example_figure(slope): # create new figure fig = plt.figure() ax = fig.add_subplot(111) # set axes equal aspect ratio ax.set_aspect('equal') # plot line given slope, # starting origin ax.plot([x * slope x in range(5)]) # output result return fig
this example code result in figures of different widths, depending on data:
example_figure(1).show()
example_figure(2).show()
matplotlib seems fit plots height, , chooses width accomodate aspect ratio. ideal outcome me opposite -- 2 plots above have same width, second plot twice tall first.
bonus — difficulty level: gridspec
in long run, create grid in one of plots has fixed aspect ratio, , again align graphs exactly.
# create 2x1 grid import matplotlib.gridspec gridspec gs = gridspec.gridspec(2, 1) # create overall graphic, containing # top , bottom figures fig = plt.figure() ax1 = fig.add_subplot(gs[0, :], aspect='equal') ax2 = fig.add_subplot(gs[1, :]) # plot lines before ax1.plot(range(5)) ax2.plot(range(5)) # show figure fig.show()
the result this:
so again, question is: how 1 create graphs vary flexibly in height depending on data, while having fixed width?
two points avoid potential misunderstandings:
- in above example, both graphs have same x-axis. cannot taken granted.
- i aware of
height_ratios
option in gridspec. can compute dimensions of data, , set ratios, unfortunately not control graphs directly, rather bounding boxes, (depending on axis labels), graphs of different widths still occur. ideally, plots' canvas aligned exactly. - another unsolved question similar, more convoluted.
any ideas , suggestions welcome, , i'm happy specify question further, if required. thank considering this!
have tried fix width fig.set_figwidth()?
Comments
Post a Comment