简体   繁体   中英

Plotting 3D data as an image in python

I have data in 3 dimensions. I would like to plot the first two dimensions and colorize by the third. I want it show up as an image like hist2d would do, except instead of being colorized by the occupation of the first two dimensions, I want it to be colorized by the third dimension. I think this will require binning everything. How can this be achieved?

Example data:

x = np.random.normal(loc=10, scale=2, size=100)
y = np.random.normal(loc=25, scale=5, size=100)
z = np.cos(x)+np.sin(y)

I want to plot x vs y and colorize by the intensity z. But, not just a scatterplot, I want it to come out as an image like this .

The easy solution, since the data is not structured on a grid is to use tripcolor from matplotlib (there is also tricontourf ):

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.random.normal(loc=10, scale=2, size=100)
y = np.random.normal(loc=25, scale=5, size=100)
z = np.cos(x)+np.sin(y)

plt.tripcolor(x, y, z);
plt.plot(x, y, '.k');

使用三色的示例

The other solution is, prior to the visualization, to interpolated the data on a regular grid using, for instance, griddata from Scipy:

from scipy.interpolate import griddata

# define the grid
x_fine = np.linspace(min(x), max(x), 200)
y_fine = np.linspace(min(y), max(y), 200)

x_grid, y_grid = np.meshgrid(x_fine, y_fine)

# interpolate the data:
z_grid = griddata((x, y), z, (x_grid.ravel(), y_grid.ravel()), method='cubic').reshape(x_grid.shape)

plt.pcolor(x_fine, y_fine, z_grid);
plt.plot(x, y, '.k');

首先使用griddata

I use ggplot for R, not so much for python, but, here's a sample:

import pandas as pd
import numpy as np
# is this the best implementation of ggplot?
from plotnine import *

x = np.random.normal(loc=10, scale=2, size=100)
y = np.random.normal(loc=25, scale=5, size=100)
z = np.cos(x)+np.sin(y)

df = pd.DataFrame({'x':x, 'y':y, 'z':z})

p = ggplot(df, aes(x='x', y='y', colour='z')) + geom_point()
p = p + scale_color_distiller(type='div', palette='RdYlBu')
p

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