Changing the scale of the x axis in a plot - python

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

Related

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

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.

Numpy Array to Graph

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:

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