How can I plot an NxN grid with Python? - python

Hi everybody I am trying to do something easy in Python but for me, nothing seems to be easy. What I want to do is to plot a grid of nxn automatically that is when I change the numbers in (make) for instance (4,4) to plot a 4X4 grid if I write (10,10) to plot a 10X10 grid, and so on. My code is below. Any help, please
import matplotlib.pyplot as plt
import numpy as np
def make(X,Y):
x, y = np.indices((X,Y))
sqr = (x==0) & (y==0)
for i in range (X):
for j in range (Y):
sqr = (x==i) & (y==j)
plt.show()
plt(sqr)
make(10,10)

Related

Plot matrix of weighted cells in grid with Matplotlib

I have a square matrix built from an array of random integers, defined below:
import numpy as np
dim_low, dim_high = 0, 20 #array of random integers' dimensions
matrix = np.random.random_integers(low = dim_low,high = dim_high, size=(dim_high,dim_high))
print(matrix) #the matrix of defined with repetitions of the array.
Resulted matrix in the picture:
https://i.stack.imgur.com/eEcCh.png
What could I do to plot the matrix generated in a grid with Matplotlib, in a way that the values of each cell (the weights) are printed in the center of each cell, and there's a scale from 0 to 20 in x an y axis, as in the picture below (notice that 'x' and 'o' are text in the example, what I need is the weights, in integer form, not text form):
https://i.stack.imgur.com/9mBuG.png (here)
I pulled most of this from this post.
import numpy as np
import matplotlib.pyplot as plt
low_dim = 0
high_dim = 20
matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))
fig, ax = plt.subplots()
for i in range(0, high_dim):
for j in range(0, high_dim):
val = matrix[i,j]
ax.text(i+0.5, j+0.5, str(val), va='center', ha='center')
ax.set_xlim(low_dim, high_dim)
ax.set_ylim(low_dim, high_dim)
ax.set_xticks(np.arange(high_dim))
ax.set_yticks(np.arange(high_dim))
ax.grid()
plt.show()
The right module for this would be seaborn. It has all the functionality you ask for and more...
Try using https://seaborn.pydata.org/generated/seaborn.heatmap.html. I won't take you through the different options because they're really well documented.
Goodluck!
BTW, you'll want to use a panda pivot table for comfortable compatibility.

Plotting a 2D contour plot from binned xyz data

EDIT: I responded in the comments but I've tried the method in the marked post - my z data is not calculated form my x and y so I can't use a function like that.
I have xyz data that looks like the below:
NEW:the xyz data in the file i produce - I extract these as x,y,z
And am desperately trying to get a plot that has x against y with z as the colour.
y is binned data that goes from (for instance) 2.5 to 0.5 in uneven bins. So the y values are all the same for one set of x and z data. The x data is temperature and the z is density info.
So I'm expecting a plot that looks like a bunch of stacked rectangles where there is a gradient of colour for one bin of y values which spans lots of x values.
However all the codes I've tried don't like my z values and the best I can do is:
The axes look right but the colour bar goes from the bottom to the top of the y axis instead of plotting one z value for each x value at the correct y value
I got this to work with this code:
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np
import scipy.interpolate
data=pandas.read_csv('Data.csv',delimiter=',', header=0,index_col=False)
x=data.tempbin
y=data.sizefracbin
z=data.den
x=x.values
y=y.values
z=z.values
X,Y=np.meshgrid(x,y)
Z=[]
for i in range(len(x)):
Z.append(z)
Z=np.array(Z)
plt.pcolormesh(X,Y,Z)
plt.colorbar()
plt.show()
I've tried everything I could find online such as in the post here: matplotlib 2D plot from x,y,z values
But either there is a problem reshaping my z values or it just gives me empty plots with various errors all to do (I think) with my z values.
Am I missing something? Thank you for your help!
Edit in reponse to : ImportanceOfBeingErnest
I tried this :
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np
import scipy.interpolate
data=pandas.read_csv('Data.csv',delimiter=',', header=0,index_col=False)
data.sort_values('sizefrac')
x=data.tempbin
y=data.sizefrac
z=data.INP
x=x.values
y=y.values
z=z.values
X=x[1:].reshape(N,N)
Y=y[1:].reshape(N,N)
Z=z[1:].reshape(N,N)
plt.pcolormesh(X,Y,Z)
plt.colorbar()
plt.show()
and got a very empty plot. Just showed me the axes and colourbar as in my attached image but pure white inside the axes! No error or anything...
And the reshaping I need to remove a data point from each because otherwise the reshaping won't work
Adapting the linked question to you problem, you should get:
import numpy as np
import matplotlib.pyplot as plt
x = list(range(10))*10
y = np.repeat(list(range(10)), 10)
# build random z data
z = np.multiply(x, y)
N = int(len(z)**.5)
Z = z.reshape(N, N)
plt.imshow(Z[::-1], extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)), aspect = 'auto')
plt.show()
The answer was found by Silmathoron in a comment on his answer above - the answer above did not help but in the comments he noticed that the X,Y data was not gridded in w way which would create rectangles on the plot and also mentioned that Z needed to be one smaller than X and Y - from this I could fix my code - thanks all

Numpy N-D Matrix to a 3D Mesh Graph

I tried looking this up a lot and there are lot of information on specific examples but they are too specific to understand.
How do I put data in a Numpy N-D Matrix to a 3D graph. please refer below example
import numpy as np
X =20
Y = 20
Z = 2
sample = np.zeros(((X,Y,Z)))
sample[1][2][2]=45
sample[1][3][0]=52
sample[1][8][1]=42
sample[1][15][1]=30
sample[1][19][2]=15
I Want to use values on X,Y,Z positions to be on a 3D graph (plot).
Thanks in advance
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
# Define size of data
P= 25
X = 70
Y = 25
Z = 3
# Create meshgrid
x,y = np.meshgrid(np.arange(X),np.arange(Y))
# Create some random data (your example didn't work)
sample = np.random.randn((((P,X,Y,Z))))
# Create figure
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
fig.show()
# Define colors
colors=['b','r','g']
# Plot for each entry of in Z
for i in range(Z):
ax.plot_wireframe(x, y, sample[:,:,:,i],color=colors[i])
plt.draw()
plt.show()
But I only want to draw X,Y,Z only.
when I used above code python throws me lots of errors like ValueError: too many values to unpack
Are you looking for something like this?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
# Define size of data
X = 20
Y = 20
Z = 3
# Create meshgrid
x,y = np.meshgrid(np.arange(X),np.arange(Y))
# Create some random data (your example didn't work)
sample = np.random.randn(X,Y,Z)
# Create figure
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
fig.show()
# Define colors
colors=['b','r','g']
# Plot for each entry of in Z
for i in range(Z):
ax.plot_wireframe(x, y, sample[:,:,i],color=colors[i])
plt.draw()
plt.show()
which would you give
There are plenty of other ways to display 3D data in matplotlib, see also here. However, you are always limited to 3 dimensions (or 4, if you do a 3D scatter plot where color encodes the 4th dimension). So you need to make a decision which dimensions you want to show or if you can summarize them somehow.
I have got something it may work for you. To understand it I explain the process I go briefly. I have connected 4x4x4 = 64 point masses to each other and created a cube with dampers and springs and inner friction. I solved the kinematic and mechanical behaviour using numpy and then I need to visualise the cube all I have is X,Y,Z points for each time step of each mass.
What I have is 4x4x4 XYZ points of a cube for each time tn:
Here how it goes :
import matplotlib.pyplot as plt
zeroPoint=points[50] # at time step 50 elastic cube in space
surf0x=zeroPoint[0,:,:,0]
surf0y=zeroPoint[0,:,:,1]
surf0z=zeroPoint[0,:,:,2]
surf1x=zeroPoint[:,0,:,0]
surf1y=zeroPoint[:,0,:,1]
surf1z=zeroPoint[:,0,:,2]
surf2x=zeroPoint[:,:,0,0]
surf2y=zeroPoint[:,:,0,1]
surf2z=zeroPoint[:,:,0,2]
surf3x=zeroPoint[nmx-1,:,:,0]
surf3y=zeroPoint[nmx-1,:,:,1]
surf3z=zeroPoint[nmx-1,:,:,2]
surf4x=zeroPoint[:,nmy-1,:,0]
surf4y=zeroPoint[:,nmy-1,:,1]
surf4z=zeroPoint[:,nmy-1,:,2]
surf5x=zeroPoint[:,:,nmz-1,0]
surf5y=zeroPoint[:,:,nmz-1,1]
surf5z=zeroPoint[:,:,nmz-1,2]
fig = plt.figure(figsize=(10,10))
wf = plt.axes(projection ='3d')
wf.set_xlim(-0.5,2)
wf.set_ylim(-0.5,2)
wf.set_zlim(-0.5,2)
wf.plot_wireframe(surf0x, surf0y, surf0z, color ='green')
wf.plot_wireframe(surf1x, surf1y, surf1z, color ='red')
wf.plot_wireframe(surf2x, surf2y, surf2z, color ='blue')
wf.plot_wireframe(surf3x, surf3y, surf3z, color ='black')
wf.plot_wireframe(surf4x, surf4y, surf4z, color ='purple')
wf.plot_wireframe(surf5x, surf5y, surf5z, color ='orange')
# displaying the visualization
wf.set_title('Its a Cube :) ')
pyplot.show()
at time step 190 same cube (animation is 60 FPS) :
The trick is as you see you need to create surfaces from points before you go. You dont even need np.meshgrid to do that. People does it for parametric z values calculation. If you have all points you dont need it.

plt.contour in Python

I would like to make a 2D contour plot given 3 numpy arrays of same size
X Y Z with (X,Y) the coordinates and Z the value at (X,Y).
Now, the function plt.contour seems to work only with a grid, and values at the intersection of the grid, and takes as input a rectangular grid only with 2D matrices as input.
see http://matplotlib.org/examples/pylab_examples/contour_demo.html
If the input for that function is (XX,YY,ZZ) then XX is a 2D rectangular array where every line is the same and every column is constant, while YY is a 2D rectangular array where every column is the same, and every line is constant.
Now, what function should I use, or what procedure should I follow, if I want to make the contour plot when the input values are NOT values taken on a grid?
thanks
Try to use plt.tricontour: http://matplotlib.org/api/pyplot_api.html?highlight=tricontour#matplotlib.pyplot.tricontour
It draws contours on an unstructured triangular grid.
Little example:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
z = x**2+np.sin(y)*y
f, ax = plt.subplots(1,1)
ax.tricontour(x,y,z)
ax.plot(x,y, 'r. ')
plt.show()

Color 2D Grid with values from separate 2D array

I have two arrays of data, x and y. I would like to plot on a scatter plot y vs. x. The range of x is [0,3] and the range of y is [-3, 3]. I then want to grid up this region into an n by m grid and color the points in each region based on the values of a separate 2D numpy array (same shape as the grid, n by m). So, the top-leftmost grid cell of my plot should be colored based on the value of colorarr[0][0] and so on. Anyone have any suggestions on how to do this? The closest I"ve found so far is the following:
2D grid data visualization in Python
Unfortunately this simply displays the colorarr, and not the 2D region I would like to visualize.
Thanks!
I think what you want is a 2 dimensional histogram. Matplotlib.pyplot makes this really easy.
import numpy as np
import matplotlib.pyplot as plt
# Make some points
npoints = 500
x = np.random.uniform(low=0, high=3, size=npoints)
y = np.random.uniform(low=-3, high=3, size=npoints)
# Make the plot
plt.hist2d(x, y)
plt.colorbar()
plt.show()
You can do it from just the color array by setting extent and aspect keywords of imshow
import matplotlib as plt
import numpy as np
zval = np.random.rand(100, 100)
plt.imshow(zvals, extent=[0,3,-3,3], aspect="auto")
plt.show()
What you get is the zval array just "crunched in" the [0:3, -3:3] range. Plot just the zval array in imshow to convince yourself of this.

Categories