Reputation: 7922
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.
Upvotes: 1
Views: 432
Reputation: 4151
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');
Upvotes: 2
Reputation: 2273
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
Upvotes: 0