Reputation: 21
I've data file containing random scattered data over x,y plane. All I want is to fill the scattered region with solid color. My data are not sorted. I've tried to use scatterplot in matplotlib but the number of points in my data file are quite large, so plotting them in scatter make the resulting plot quite big in size. The scattered data form small islands over the x,y plane.
Upvotes: 2
Views: 6667
Reputation: 35513
You can calculate a histogram (2D) of the x, y values using numpy's histogram2d method. Then you plot the array that is true for all non-zero bins and false for all zero bins. You can control the resolution of the histogram using the bins
parameter. This method returns a tuple of 3 arrays: the 2D histogram and two 1D arrays corresponding the bin steps along each 'edge' (x then y). You can control the step values using the range
parameter.
For example:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(101)
x = np.random.normal(0,1,10000)
y = np.random.normal(0,1,10000)
hist,xedge,yedge= np.histogram2d(x,y,bins=100,range=[[-4,4],[-4,4]])
plt.imshow(hist==0,
origin='lower',
cmap=plt.gray(),
extent=[xedge[0],xedge[-1],yedge[0],yedge[-1]])
plt.savefig('hist2d.png')
plt.show()
This results in:
The black points show where you have any data, the white points are where there is no data. The histogram is presented using the imshow
method, which is used to plot images or matrices. By default it set's the origin to the top left, so you will either want to change the parameter origin='lower'
, or you want to appropriately adjust the extent
parameter, which controls the range values: [intial x, final x, initial y, final y]. You can control the color scheme by adjusting the color map.
As @joaquin mentions in the comments, you can also simply plot imshow(hist)
to see the full range of values (heatmap), rather than 0 or 1.
Upvotes: 3
Reputation: 952
import numpy as np
import matplotlib.pylab as plt
x=np.random.rand(10)
y=np.random.rand(10)
plt.figure()
plt.fill(x,y,'b')
plt.show()
There is also a fill_between to fill between two lines matplotlib documentation of them both
Upvotes: 0