I use Matplotlib to generate PNG files of scatterplots. Now, for each scatterplot, in addition to a PNG file, I would also like to generate a list of pixel coordinates of the various points in the scatterplot.
The code I use to generate the PNG files for the scatterplots is basically like this:
from matplotlib.figure import Figure
from matplotlib.pyplot import setp
from matplotlib.backends.backend_agg import FigureCanvasAgg
...
fig = Figure(figsize=(3, 3), dpi=100)
ax = fig.gca()
for (x, y), m, c in zip(points, markers, colors):
ax.scatter(x, y, marker=m, c=c, s=SIZE, vmin=VMIN, vmax=VMAX)
# several assorted tweaks like ax.spines['top'].set_color('none'), etc.
setp(fig, 'facecolor', 'none')
# FigureCanvasAgg(fig).print_png(FILEPATH)
...(where the variables in UPPERCASE stand for settable parameters).
How can I also produce a list of (px, py)
pairs of the pixel coordinates in the resulting PNG corresponding to the points in points
?
[EDIT: removed some nonsense about imshow
.]
[EDIT:
OK, here's what I finally came up with, based on Joe Kington's suggestions.
# continued from above...
cnvs = FigureCanvasAgg(fig)
fig.set_canvas(cnvs)
_, ht = cnvs.get_width_height()
pcoords = [(int(round(t[0])), int(round(ht - t[1]))) for t in
ax.transData.transform(points)]
fig.savefig(FILEPATH, dpi=fig.dpi)
The resulting pixel coords (in pcoords
) are pretty close to the correct values. In fact, the y coords are exactly right. The x coords are 1 or 2 pixels off, which is good enough for my purposes.
]
See Question&Answers more detail:
os