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

I am tired of manually creating graphs in excel and, therefore, I'm trying to automate the process using Python to massage CSV data into a usable form and matplotlib to build the result.

Using matplotlib and generating them is not a problem, but I cannot decide how to set the aspect ratio / resolution of the output.

In particular, I am trying to generate scatterplots and graphs of stacked areas. Everything I tried seems to result in one or more of the following:

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

If anyone has examples showing how to achieve this result, I would be very grateful!

+4
source share
3 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 ( jterrace already mentioned) is to use the figsize parameter in plt.figure : for example. fig = plt.figure(figsize=(3,1)) . However, the two methods are slightly different: a figure can contain many axes. figsize controls the aspect ratio for the whole picture, and set_aspect controls the aspect ratio for a particular axis.

You can then trim the unused space around the graph with bbox_inches='tight' :

 plt.savefig('/tmp/test.png', bbox_inches='tight') 

enter image description here

If you want to get rid of excess empty space due to the automated selection of x-range and y-range of matplotlib, you can manually set them using ax.set_xlim and ax.set_ylim :

 ax.set_xlim(0, 1) ax.set_ylim(0, 1) 

enter image description here

+5
source

Aspect ratio / graph size

The easiest way I found for 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 high:

 import matplotlib.pyplot as plt fig = plt.figure(figsize=(4,3)) 

Interval Adjustment

To do this, there is a function called subplots_adjust , which allows you to change the boundary area of ​​the graph itself, leaving more space for the name, axis and labels. Here is an example from one of my graphs:

 plt.gcf().subplots_adjust(bottom=0.15, left=0.13, right=0.95, top=0.96) 
+3
source

For resolution, you can use the dpi (dots per inch) argument when creating a shape or in the savefig () function. For high quality prints, dpi = 600 or more is recommended.

0
source

Source: https://habr.com/ru/post/1381382/


All Articles