-1

I need to set the dimension of a chart exactly. I tried this, but the result is not what I expected (both if I set px and cm). In addiction, I would like to know how to export correctly the image.

import numpy as np

plt.rcParams['figure.dpi']=100
  
# create data
x = ['A', 'B', 'C', 'D']
y1 = np.array([10, 20, 10, 30])
y2 = np.array([20, 25, 15, 25])
y3 = np.array([12, 15, 19, 6])
y4 = np.array([10, 29, 13, 19])
  
# plot bars in stack manner
cm = 1/2.54  # centimeters in inches
px = 1/plt.rcParams['figure.dpi']  # pixel in inches

plt.figure(figsize=(800*px,1000*px))

plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='b')
plt.bar(x, y3, bottom=y1+y2, color='y')
plt.bar(x, y4, bottom=y1+y2+y3, color='g')
plt.xlabel("Teams")
plt.ylabel("Score")
plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"])
plt.title("Scores by Teams in 4 Rounds")
plt.show()

Dimensions expected: 800px x 1000 px, dpi= 100 I attach here a screenshot from Photoshop of the exported image Not correct dimensions!

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • Exactly, how are you saving your figure, from what backend, and are you using a custom rcParams? Your stated dimensions do not even have the correct 8:10 aspect ratio, so you are doing something strange, with my best-guess being that you are calling `savefig(fname, bbox_inches='tight')` – Jody Klymak Jun 08 '21 at 16:07
  • I posted all the code I wrote. Consider that I'm a beginner, so probably I'm doing something wrong. :) I try to be more clear: I need to write a code that let me export the chart with dimensions (in pixels) I want. – Nicola Talamonti Jun 08 '21 at 18:31
  • How did you save the png you later inspected? – Jody Klymak Jun 08 '21 at 19:37
  • I save it only by right clicking the chart and selecting "Save image as"... I tried to use also `plt.savefig(fname, bbox_inches='tight')` but it still doesn't work. – Nicola Talamonti Jun 09 '21 at 06:49
  • Do plt.savefig(fname, dpi=100). Right clicking in the image (I assume in a notebook of some sort?) will not return you a nice image. – Jody Klymak Jun 09 '21 at 15:08
  • I tried to use also `plt.savefig(fname, bbox_inches='tight')` but it still doesn't work. – Nicola Talamonti Jun 11 '21 at 08:38
  • “It still doesn’t work” is not helpful. I also did _not_ say to use bbox_inches=tight. – Jody Klymak Jun 11 '21 at 15:11

1 Answers1

0

The Figure constructor accepts a tuple (numbers in inches) with a default of 80 dpi. You'll want to pass a dpi argument to change this

from matplotlib.figure import Figure

fig = Figure(figsize=(5, 4), dpi=80)

The above is 5 inches by 4 inches at 80dpi, which is 400px by 320px

if you want 800 by 1000 you can do

fig = Figure(figsize=(8, 10), dpi=100)

Exporting an image is as simple as

fig.savefig("MatPlotLib_Graph.png", dpi = 100)
Harry
  • 193
  • 1
  • 12