ucag
ucag

Reputation: 487

How to draw a figure in specific pixel size with matplotlib?

Right now I'm working on a graphic project which requires me to draw a image that has specific element size in micrometer. And I'm using matplotlib to finish this task. However, I meet some problems in size control.

I've calculated all the plot data to describe the image. It basically is a grid with scatters on grid's cross line and there are hundreds of columns and rows in this grid and each axis for each cross line has its own width in micrometer as its size unit. Example image is just like this: example

I've tried many ways to control element or artist size. For making one pixel equals to one micrometer, I set a large DPI to the figure

DPI = 25400
plt.figure(dpi=DPI)
fig = plt.gcf()
size = (
    width / DPI,
    height / DPI
)
fig.set_size_inches(size)

this can ensure that one pixel is one micrometer. However, I don't know how to control scatter and line width in pixel size. the default s in plt.scatter or linewidth in plt.plot can't help to control the size.

I want to know how to control it in micrometers with matplotlib or should I just change another tool to draw this graph or even any other tools to meet this requirement?

Upvotes: 1

Views: 2762

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

Matplotlib's linewidth is in points; scatter size is in points^2. For this see pyplot scatter plot marker size.

1 point == fig.dpi/72. pixels

Hence,

1 pixel == 72/fig.dpi points

If one micron is one pixel, and you want something of a size x microns,

x microns = x pixel = x*72 /fig.dpi points

hence

plt.plot(..., linewidth=x * 72 / fig.dpi)
plt.scatter(..., s=(x * 72 / fig.dpi)**2)

Upvotes: 6

Related Questions