I'm fed up with manually creating graphs in excel and consequently, I'm trying to automate the process using Python to massage the .csv data into a workable form and matplotlib to plot the result.
Using matplotlib and generating them is no problem but I can't work out is how to set the aspect ration / resolution of the output.
Specifically, I'm trying to generate scatter plots and stacked area graphs. Everything I've tried seems to result in one or more of the following:
If anyone has some working examples showing how to achieve this result I'd be very grateful!
You can control the aspect ratio with ax.set_aspect
:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax=fig.add_subplot(1,1,1)
ax.set_aspect(0.3)
x,y=np.random.random((2,100))
plt.scatter(x,y)
Another way to set the aspect ratio (already mentioned by jterrace) is to use the figsize
parameter in plt.figure
: e.g. fig = plt.figure(figsize=(3,1))
. The two methods are slightly different however: A figure can contain many axes. figsize
controls the aspect ratio for the entire figure, while set_aspect
controls the aspect ratio for a particular axis.
Next, you can trim unused space from around the plot with bbox_inches='tight'
:
plt.savefig('/tmp/test.png', bbox_inches='tight')
If you want to get rid of the excess empty space due to matplotlib's automated choice of x-range and y-range, you can manually set them with ax.set_xlim
and ax.set_ylim
:
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
The easiest way I've found to do this is to set the figsize
parameter to the figure function when creating the figure. For example, this would set the figure to be 4 inches wide by 3 inches tall:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4,3))
For this, there is a function called subplots_adjust that allows you to change the bounding region of the graph itself, leaving more room for the title, axes, and labels. Here's an example from one of my graphs:
plt.gcf().subplots_adjust(bottom=0.15, left=0.13, right=0.95, top=0.96)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With