简体   繁体   中英

Matplotlib 3D plot use colormap

I am trying to use ax.scatter to plot a 3D scattering plot. I've read the data from a fits file and stored data from three column into x,y,z. And I have made sure x,y,z data are the same size. z has been normolized between 0 and 1.

import numpy as np
import matplotlib
from matplotlib import pylab,mlab,pyplot,cm
plt = pyplot
import pyfits as pf
from mpl_toolkits.mplot3d import Axes3D
import fitsio

data = fitsio.read("xxx.fits")

x=data["x"]
y=data["y"]
z=data["z"]
z = (z-np.nanmin(z)) /(np.nanmax(z) - np.nanmin(z))

Cen3D = plt.figure()
ax = Cen3D.add_subplot(111, projection='3d')

cmap=cm.ScalarMappable(norm=z, cmap=plt.get_cmap('hot'))
ax.scatter(x,y,z,zdir=u'z',cmap=cmap)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

What I am trying to achieve is use color to indicate the of size of z. Like higher value of z will get darker color. But I am keep getting a plot without the colormap I want, they are all the same default blue color. What did I do wrong? Thanks.

You can use the c keyword in the scatter command, to tell it how to color the points.

You don't need to set zdir , as that is for when you are plotting a 2d set

As @Lenford pointed out, you can use cmap='hot' in this case too, since you have already normalized your data.

I've modified your example to use some random data rather than your fits file.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

z = (z-np.nanmin(z)) /(np.nanmax(z) - np.nanmin(z))

Cen3D = plt.figure()
ax = Cen3D.add_subplot(111, projection='3d')

ax.scatter(x,y,z,cmap='hot',c=z)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

在此输入图像描述

As per the pyplot.scatter documentation , the points specified to be plotted must be in the form of an array of floats for cmap to apply, otherwise the default colour (in this case, jet) will continue to apply.

As an aside, simply stating cmap='hot' will work for this code, as the colour map hot is a registered colour map in matplotlib.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM