Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can square-shaped images be saved using matplotlib?

My goal is to create a number of matplotlib plots and then to arrange them in a large array. For this purpose, I need to ensure that the output images of matplotlib plots are square. How can this be done?

Here's a segment of my code:

figure = matplotlib.pyplot.figure()
figure.suptitle(label, fontsize = 20)
#figure.set_size_inches(19.7, 19.7)
matplotlib.pyplot.scatter(
    variable_1_values,
    variable_2_values,
    s          = marker_size,
    c          = "#000000",
    edgecolors = "none",
    label      = label,
)
matplotlib.pyplot.xlabel(label_x)
matplotlib.pyplot.ylabel(label_y)
legend = matplotlib.pyplot.legend(
    loc            = "center left",
    bbox_to_anchor = (1, 0.5),
    fontsize       = 10
)
print("save {filename}".format(filename = filename))
matplotlib.pyplot.savefig(
    filename,
    bbox_extra_artists = (legend,),
    bbox_inches        = "tight",
    dpi                = 700
)

I know how to set the figure to square, what I need is the output image set to square. This would be conceptually as simple as taking the default output image and then extending its background as necessary to make the image square.

like image 646
d3pd Avatar asked Sep 15 '26 20:09

d3pd


1 Answers

Not sure if this is what you are looking for, but it produces a 600x600 pixel png image for me.

import numpy as np
import matplotlib.pyplot as plt

a = np.random.normal(size=1000)
b = np.random.normal(size=1000)

fig = plt.figure(figsize=(6,6))

plt.plot(a,b,'g.')
plt.xlabel("x axis label")
plt.ylabel("y axis label")
plt.title("Random numbers in a scatter plot")

fig.savefig("test.png")
like image 92
Alex Avatar answered Sep 18 '26 10:09

Alex