matplotlib: how can I convert a XYZ scatter to a pixel image?

馋奶兔 提交于 2019-12-10 10:26:14

问题


I'm looking for some way in to convert a scatter plot (X vs Y, color normalized by Z) into a 2D "pixel" image. I.e. how can I plot a pixelized image where the pixels are colored according to a third variable?

In my case, I have a list of galaxies, each a with sky coordinate (X,Y) and a distance (Z). I want to make a pixelized image of X vs Y, with the pixels color normalized according to Z (e.g. the median Z value for the galaxies in that pixel).

I know I could do something like this with hexbin, but I would like to have square pixels, not hexagons. (Something more like what imshow produces).

I'm still learning python, so if there is a simple/quick way to do this (or clear instructions on how to do it the complicated way!) that'd be great.

Any help would be much appreciated!


回答1:


Okay - there are two ways that you can do this. One would be for you to have a discreet number of bins for the distances (like d < 10pc, 10pc < d < 20pc, d> 20pc). This is relatively easy, all you need to do are a few loops - here is an example with 3:

raclose = []
ramid = []
rafar = []
decdlose = []
decmid = []
decfar = []

for ii in range(len(dist)):
  if dist[ii] < 10.:
    raclose.append(ra[ii])
    decclose.append(dec[ii])
  elif dist[ii] > 20.:
    rafar.append(ra[ii])
    decfar.append(dec[ii])
  else:
    ramid.append(ra[ii])
    decmid.append(dec[ii])

plt.clf
ax1 = scatter(raclose, decclose, marker='o', s=20, color="darkgreen", alpha=0.6)
ax2 = scatter(ramid, decmid, marker='o', s=20, color="goldenrod", alpha=0.6)
ax3 = scatter(rafar, decfar, marker='o', s=20, color="firebrick", alpha=0.6)
line1 = Line2D(range(10), range(10), marker='o', color="darkgreen")
line2 = Line2D(range(10), range(10), marker='o',color="goldenrod")
line3 = Line2D(range(10), range(10), marker='o',color="firebrick")
plt.legend((line1,line2,line3),('d < 10pc','20pc > d > 10pc', 'd > 20pc'),numpoints=1, loc=3)
show()

Or you can do a contour plot, such that you stipulate RA on the x-axis and Dec on the y-axis and fill in the plot with the distances. Both RA and Dec are 1D arrays with the respective coordinates. Then you make a 2D array with the distance. Determine what the median/mean value of the distances are and then divide the 2D array by that value to normalize it. Finally, plot using a contour plot (using contourf or imshow), like:

import matplotlib.pyplot as plt
from matplotlib import cm
ax = pylab.contourf(RA,Dec,dists, levels=[1, 5, 10, 15], cmap=plt.cm.spectral)
cbar=pylab.colorbar()


来源:https://stackoverflow.com/questions/7988473/matplotlib-how-can-i-convert-a-xyz-scatter-to-a-pixel-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!