Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?

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:

  • Cramped graph areas (small plot area covered with the legend, axes etc.).
  • The wrong aspect ratio.
  • Large spaces on the sides of the chart area (I want a very wide / not very tall image).

If anyone has some working examples showing how to achieve this result I'd be very grateful!

like image 902
Jon Cage Avatar asked Feb 23 '23 09:02

Jon Cage


2 Answers

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

enter image description here

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)

enter image description here

like image 82
unutbu Avatar answered Feb 24 '23 23:02

unutbu


Aspect Ratio / Graph Size

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

Adjusting Spacing

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)
like image 23
jterrace Avatar answered Feb 25 '23 00:02

jterrace