filling a Mat Plot Lib Scatter plot with points using a loop - python

I tried this but got an error that they are not the same size
x = np.linspace(0,501,num=50)
y = np.linspace(0,501,num=50)
for i in range(10,510,10):
plt.scatter(x,i,c='dimgrey')
ax = plt.gca()
ax.set_facecolor('darkgrey')
plt.xlim(0,501)
plt.ylim(0,501);
My overall goal is to have N amount of points plotted in a grid orientation in the scatter plot. I was tying to plot 2500 points like this.
All I could come up with was one row or column would equal 50 points,
and I made this loop.
I want to fill the plot like this: a line of points at y= 10 as I have here, then at 20,30,40... so on. I realize I could do this manually but is there an easier way I could incorporate it into the loop? I am planning on putting it into an animation later.

Here is an simple example, starting from your code.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,501,num=50)
for i in range(10,40,10):
y = i * np.ones(50)
plt.scatter(x,y)
This gives the following plot :

Related

How can i change the look of my surface plot? I want it to look like a grid an not like a solid surface

I'm trying to generate a 3d plot from a few datapoints. My goal is it, to compare two different datasets and show how good they match at different points. Right now I'm working on the first surface and my supervisor is unhappy with the visualization.
I use the following code at the moment:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
# Create the figure and axes objects
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Define the data for the first surface
x1 = [25,35,40,45,50,55,60]
y1 = [1300,4000,5000,5400]
z1 = [8.06,5.81,5.10,4.55,4.1,3.01,2.51,6.46,4.93,4.4,4.03,3.15,2.83,2.4,5.95,4.6,3.87,3.19,2.91,2.7,2.36,5.69,4.29,3.63,3.1,2.85,2.65,2.33]
# Convert the z1 data to 2D arrays
x, y = np.meshgrid(x1, y1)
z1 = np.array(z1).reshape(x.shape)
# Plot the first surface
ax.plot_surface(x, y, z1)
# Show the plot
plt.show()
And as a result the following plot is displayed:
enter image description here
My supervisor wants it to look something like this:
enter image description here
Note that this is a completly different diagram with a different dataset and also different axes.
I wonder if it is even possible to generate such a high resolution of a grid with so few datapoints.
Has is something to do with the way the points are connected in the diagram? In my diagram it looks like a linear interpolation. Is it possible to influence the interpolation?
I would be glad if anyone has an idea and is able to help me.
Thanks, and all the best!

Vertically draw plot with matplotlib where each row in an array is a line

I have a dataset, an even numpy array where each row represents a line:
matrix = np.random.rand(10,10)
Ultimately, I would like a graph like this:
Which I have made before in R. But I can't get it to work in Python. I'm not too proficient yet with Python, and have to use it this time.
I simply plot with:
plt.plot(matrix)
Which results in a good starting point:
My first step would be to flip the x and y axis, but the plot function requires an x_vals and y_vals, which my array does not have. There are just values. How can I (for starters) swap the x- and y-axis so that each row in the array gets drawn as an individual vertical line as shown in the image above?
If you don't provide x values, matplotlib will just use a range.
Try:
import numpy as np
import matplotlib.pyplot as plt
matrix = np.random.rand(10,10)
x_vals = np.arange(10)
for y_vals in matrix:
plt.plot(y_vals, x_vals)
plt.show()

How to extract polar plot information in Python?

I want to extract polar coordinates from the plot. There exists a matrix that has 10 rows and 2 columns a and b. This matrix has the numbers that created the polar plot.
But what I am looking for is a matrix that has the polar coordinates that are already plotted.
Example: the first row (meaning, information about the first point) would include the x,y,radius and theta/angle or any other useful information from the plot that were previously not there in the original matrix.
Think of polar plotting as a transformation that was implemented on the matrix in the for loop and I want to extract the new numbers resulted from the output polar plot.
import matplotlib.pyplot as plt
sample= [1,2,3,4,5,6,7,8,9,10]
fig = plt.figure()
fig.add_subplot(111, projection='polar')
data = sample
for i in data:
a=i+min(data)
b=i+max(data)
plt.polar(a,b, '.', c='black')
plt.show()
Even after your clarification I am a little confused by the code example. But I am pretty sure the code below answers your question.
import numpy as np
import matplotlib.pyplot as plt
x = np.random.random((10,1)) # same as "a" in your example
y = np.random.random((10,1)) # same as "b" in your example
plt.plot(x,y)
plt.title("Rectangular coordinates")
plt.show()
th = np.arctan2(y,x)
r = np.sqrt(x**2 + y**2)
# Should show the same plot as above, just with different margins/aspect ratio/grid lines
plt.polar(th,r)
plt.title("Polar coordinates")
plt.show()
It's just as easy to go in reverse, getting the rectangular coordinates if you assume your random data is representing data in polar coordinates.

matplotlib imshow how to plot points instead of image?

Here is the code:
plots=imshow(Z,extent=extent,origin,cmap=cmap,aspect='auto',vmin=vmin,vmax=vmax)
plots.plot(Response,component,vrange)
It plots an image based on data list Z, how can I let it print data points instead of an image?
Looks like needs to change to scatter(x, y,...) to plot data points, how difficult it is to change array Z to x, y?
As #jdj081 said, you want to produce a scatter plot.
import os.path
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# get an image from the sample data directory
fname = os.path.join(matplotlib.get_data_path(), 'sample_data', 'lena.png')
im = plt.imread(fname)
# Reduce the data by a factor of 4 (so that we can see the points)
im = im[::4, ::4]
# generate coordinates for the image. Note that the image is "top down", so the y coordinate goes from high to low.
ys, xs = np.mgrid[im.shape[0]:0:-1, 0:im.shape[1]]
# Scatter plots take 1d arrays of xs and ys, and the colour takes a 2d array,
# with the second dimension being RGB
plt.scatter(xs.flatten(), ys.flatten(), s=4,
c=im.flatten().reshape(-1, 3), edgecolor='face')
plt.show()
You didn't provide much information to go on, but it sounds like you really want to create a scatter plot.
There are many options here depending on what you are plotting and what you want to see, but I have found the following helpful:
Fixing color in scatter plots in matplotlib
import pylab
pylab.figure(1)
pylab.plot([1,2,3,4],[1,7,3,5]) # draw on figure one
pylab.show() # show figure on screen

Is there a way to make multiple horizontal boxplots in matplotlib?

I am trying to make a matplotlib figure that will have multiple horizontal boxplots stacked on one another. The documentation shows both how to make a single horizontal boxplot and how to make multiple vertically oriented plots in this section.
I tried using subplots as in the following code:
import numpy as np
import pylab as plt
totfigs = 5
plt.figure()
plt.hold = True
for i in np.arange(totfigs):
x = np.random.random(50)
plt.subplot('{0}{1}{2}'.format(totfigs,1,i+1))
plt.boxplot(x,vert=0)
plt.show()
My output results in just a single horizontal boxplot though.
Any suggestions anyone?
Edit: Thanks to #joaquin, I fixed the plt.subplot call line. Now the subplot version works, but still would like the boxplots all in one figure...
If I'm understanding you correctly, you just need to pass boxplot a list (or a 2d array) containing each array you want to plot.
import numpy as np
import pylab as plt
totfigs = 5
plt.figure()
plt.hold = True
boxes=[]
for i in np.arange(totfigs):
x = np.random.random(50)
boxes.append(x)
plt.boxplot(boxes,vert=0)
plt.show()
try:
plt.subplot('{0}{1}{2}'.format(totfigs, 1, i+1) # n rows, 1 column
or
plt.subplot('{0}{1}{2}'.format(1, totfigs, i+1)) # 1 row, n columns
from the docstring:
subplot(*args, **kwargs)
Create a subplot command, creating axes with::
subplot(numRows, numCols, plotNum)
where plotNum = 1 is the first plot number and increasing plotNums
fill rows first. max(plotNum) == numRows * numCols
if you want them all together, shift them conveniently. As an example with a constant shift:
for i in np.arange(totfigs):
x = np.random.random(50)
plt.boxplot(x+(i*2),vert=0)

Categories

Resources