Numpy Array to Graph - python

I have a simple 2D Numpy array consisting of 0s and 1s. Is there a simple way to make a graph that will shade in corresponding coordinates?
For example if my array was [[1,0],[0,1]]
The plot would be a 2x2 square with the top left and bottom right shaded in

You can use matplotlib to plot a matrix for you.
Use the matshow command with an appropriate colourmap to produce the plot.
For example
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,0],[0,1]])
plt.matshow(x, cmap='Blues')
plt.show()
would produce:

Related

Controlling the Axis of a NumPy Histogram

I have a sorted, 1D NumPy array which contains 156k integers that range from 263,168 to 24,064,000. I don't know how the items in the array are distributed so I am trying to plot the data as a histogram.
I've tried setting different values for the bins parameter but I still end up with a plot that doesn't allow me to see the distribution.
import numpy as np
from matplotlib import pyplot as plt
np_ary = # integer array of data
print(np_ary)
plt.hist(np_ary, bins='auto')
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.

Changing the scale of the x axis in a plot

Let's say I have a 2D array I plot using imshow. I want to be able to scale the x axis to the percent of the x axis. So I plot the data like this:
import numpy as np
import matplotlib.pyplot as plt
A = np.random.random((10,10))
plt.show(plt.imshow(A,origin='low', extent=[0,10,0,10]))
Now I'm not sure how I can do that. Any insight?
EDIT: fixed to include extent as #tcaswell pointed out

How to draw a matrix sparsity pattern with color code in python?

I am using spy from matplotlib.pyplot to draw the sparsity pattern of a csc_matrix from scipy.sparse like this
>>> import scipy.sparse as sprs
>>> import matplotlib.pyplot as plt
>>> Matrix=sprs.rand(10,10, density=0.1, format='csc')
>>> plt.spy(Matrix)
>>> plt.show()
I want to do the same but give colors to the matrix elements according to their magnitude.
Is there a simple way to make spy do this? If not, is there another way to do it?
You could use imshow:
d=Matrix.todense()
plt.imshow(d,interpolation='none',cmap='binary')
plt.colorbar()
Gives:
I had a similar problem. My solution: use a scatter plot with a color bar.
Basically I had a 100 by 100 sparse matrix, but I wanted to visualize all the points and the values of the points.
imshow is not a good solution for sparse matrices, as in my experience it might not show all the points! For me this was a serious issue.
spy is reliable for sparse matrices, but you can't add a colorbar.
So I tried to extract the non-zero values and plot them in a scatter plot and add a color bar based on the value of the non-zero elements.
Example below:
import numpy as np
import matplotlib.pyplot as plt
# example sparse matrix with different values inside
mat = np.zeros((20,20))
mat[[1,5,5,5,10,15],[1,4,5,6,10,15]] = [1,5,5,5,10,15]
fig,ax = plt.subplots(figsize=(8, 4), dpi= 80, facecolor='w', edgecolor='k')
# prepare x and y for scatter plot
plot_list = []
for rows,cols in zip(np.where(mat!=0)[0],np.where(mat!=0)[1]):
plot_list.append([cols,rows,mat[rows,cols]])
plot_list = np.array(plot_list)
# scatter plot with color bar, with rows on y axis
plt.scatter(plot_list[:,0],plot_list[:,1],c=plot_list[:,2], s=50)
cb = plt.colorbar()
# full range for x and y axes
plt.xlim(0,mat.shape[1])
plt.ylim(0,mat.shape[0])
# invert y axis to make it similar to imshow
plt.gca().invert_yaxis()

horizontal plot in python

I am looking for a plot that is rotated 90 degree in clockwise directions. An similar example of such plot is "hist(x, orientation='horizontal')". Is there any way to achieve similar orientation.
#Make horizontal plots.
import random
import matplotlib.pyplot as plt
x = random.sample(range(1000), 100)
x
plt.plot(x) #orientation='horizontal'
plt.show()
plt.plot(x) plots your x values automatically against the y-axis. In order to get a rotated plot you have to plot your x values against the x axis. So you'll need a to make vector for the y-axis, which has the same length as your sample.
import random
import matplotlib.pyplot as plt
import numpy as np
x=random.sample(1000)
y=np.arange(1000)
plt.plot(x,y)
Using plt.plot(x), matplotlib takes your x-values as its y-values and generates a vector for the x axis automatically.

Categories