Home > python - Discrete density plot in matplotlib

## python - Discrete density plot in matplotlib

I have a 2D numpy array and I want to create a discrete density plot using it. Discrete in the sense that at each point (i,j) on the plot a dot should be placed whose color should correspond to the value of the (i,j) th element of the 2D array. I do not want to use imshow because I do not want any interpolation and I also want to control the size the dots to be placed.

python matplotlib plot density-plot
|
this question
edited Aug 12 '13 at 7:35 Saullo Castro 27.1k 8 77 138 asked Jul 31 '13 at 12:10 lovespeed 1,144 9 21 42

|

Have you tried imshow with interpolation='nearest'? Is this close to what you want?

import matplotlib.pyplot as plt
import numpy as np

data = np.arange(100).reshape(10, 10)
fig, ax = plt.subplots()
ax.imshow(data, interpolation='nearest')
plt.show()


|
answered Jul 31 '13 at 12:29 unutbu 426k 61 841 946

|

You can always do this explicitly for each point, but this will be slow. I think it is best to do it line by line (keep say y fixed) and use the scatter function.

import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D

n = 100
x = plt.linspace(0,5, n)
y = plt.linspace(0,5, n)

ax = plt.subplot(111)
for i in range(n):
y_fixed = y[i] * plt.ones(n)
z = [(abs(plt.cos(x[i])), 0.0, 0.5) for i in range(n)]
ax.scatter(x, y_fixed, c=z)

plt.show()


The size is also adjustable in this manor using the s argument.

bhalos['SubhaloBHMass'] * 1e10 / 0.704) # in units of M_sol h^-1logx = np.log(x)logy = np.log(y)plt.plot(logx, logy, '.')plt.ylabel('$\log(M_{BH}$ / M$_{\odot}$)' )plt.xlabel(' $\log(\sigma_{1D}$ / km s$^{-1}$)')plt.title('\$M_{BH}-

Without any data on how you want the color specified I used an RGB value. You may need to normalise however c= will take anything pretty much and turn it into a colour, but that may not be very relevant to you.

For more with scatter see the demo here

|
answered Jul 31 '13 at 12:41 Greg 5,747 16 34      I cannot really understand how to implement this in my case as I have a 2D array. Could you show me how to do it with a 2D array? –  lovespeed Jul 31 '13 at 12:55      You take a slice from your 2D array corresponding to a fixed y (or x). And use that as the color argument e.g c=array[i]. –  Greg Jul 31 '13 at 13:06