Plotting a simple 2D vector - python

New to Python and just trying to accomplish what I think must be the simplest of tasks: plotting a basic 2D vector. However my online search has gotten me nowhere so I turn to stackoverflow with my very first question.
I Just want to plot a single 2D vector, let's call it my_vector. my_vector goes from (0,0) to (3,11).
What I have done is this:
from __future__ import print_function
import numpy as np
import pylab as pl
%pylab inline
x_cords = np.arange(4)
y_cords = np.linspace(0, 11, 4)
my_vector = vstack([x_cords, y_cords])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(my_vector)
plt.show()
Which gives the following image (and totally not what I am after):
a very wrong plot
However I have found that
ax.plot(x_cords, y_cords)
instead of
ax.plot(my_vector)
gives me the plot I am looking for but then I don't have that single vector I am after.
So how does one correctly plot a basic 2D vector? Thank you and sorry if this has indeed been posted somewhere else...

You can also unpack your 2D vector
pl.plot(*my_vector)
Which is effectively just doing
pl.plot(x_cords, y_cords)

Related

Is there a 3d plotting function similar to Axes.imshow()?

Ive got test MRI data that I would like to make a 3D plot of. Right now I am visualising each slice individually though using the axes.imshow() function. Is there a 3d equivalent?
Taking the following example, is there anyway to get a black cube out of data in the following example, as opposed to just black square slices of it? That will solve my issue.
Example:
import numpy as np
import matplotlib.pyplot as plt
data = np.zeros((200,200,200))
slice_0 = data[0,:,:]
fig,axes = plt.subplots()
axes.imshow(slice_0.T, cmap="gray")
output

Plotting from array to geoviews/holoviews. Converting to xarray needed?

First of all, if anyone has a link to a good tutorial to creating colomaps with geoviews or holoviews and transporting that to a dashbooard please send a link. I am trying to mimick what they did at the timestamp in the video here . Also having a hard time finding good documentation of geoviews other than the few examples on their website, so a point to the full docs would be great.
Anyways, I have a pretty basic plot I think. It a mesh of x a mesh of y and a mesh of a z value. I want to plot this in geoviews. It contains interpolated motions from GPS stations basically and I want to make a colormap of the z value. I can plot this really easily with matplotlib with a simple
plot = plt.scatter(mesh_x, mesh_y, c = z1, cmap = cm.hsv)
but trying to get this into geoviews makes a really funky dataframe.
running print(np.shape(mesh_x),np.shape(mesh_y), np.shape(z1)) shows the shape of all of these are (41,348). If I try to put them into a single array with a = np.array((mesh_x,mesh_y,z1)) I get an array of shape (3,41,348) as expected. From here I am really just guessing on what to do. When I try to put this into a geoviews points data frame with
points = [a[0], a[1], a[2]]
df = gv.Points(points)
df.dframe()
and then run df.dframe() it shows two columns, longitude and lattitude with incorrect values, here is a screenshot of what it shows if its helpful
I have tried converting to an xarray because it seems that is preferred in all the examples shown on geoviews website but that looks funky as well. When I try xrtest = xr.DataArray((mesh_x,mesh_y,z1)) I get a xarray that looks like this
At this point I have no idea what to do. I have tried a few different ways that I though may work but I can't remember all of them. This is where I am at now. I am sure I am doing something completely wrong, I just have no idea how to do it correctly. Thank you
Assuming you want a points plot as you are using in Matplotlib, the HoloViews equivalent to plt.scatter is hv.Points. hv.Points accepts a tidy data format that you can get by transposing the data compared to Matplotlib:
import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
mesh_x = [1,2,3,6]
mesh_y = [6,2,8,0]
z1 = [0.5, 4, 6,2]
plot = plt.scatter(mesh_x, mesh_y, c = z1, cmap = cm.hsv)
import holoviews as hv
hv.extension('matplotlib')
hv.Points(zip(mesh_x,mesh_y,z1), kdims=["x","y"], vdims=["z"]).opts(color='z', cmap="hsv")
Here kdims=["x","y"], is optional but is explicit about the key dimensions you want. You may also want to consider hvPlot, which handles the same data format as plt.scatter:
import pandas as pd
df = pd.DataFrame(dict(x=mesh_x,y=mesh_y,z=z1))
import hvplot.pandas
df.hvplot.scatter(x="x", y="y", c="z", cmap="hsv")

Python code with for loop that did not work

I have run the following code but it showed an empty plot with nothing plotted and I am not able to know the reason
Please help
import matplotlib.pyplot as plt
import math
for xx in range(10,100000,1000):
plt.plot(xx,math.sqrt((.30*(1-.3))/(xx-1)))
If you are trying to plot each point individually, try using plt.scatter() like this:
for xx in range(10,100000,1000):
plt.scatter(xx, math.sqrt((.30*(1-.3))/(xx-1)))
If you're looking to plot a continuous line, you'll want to make your vectors beforehand and then pass them to plt.plot(). I suggest using numpy since np.arrays can handle vectorized data
import numpy as np
# Make x vector
xx = np.arange(10,100000,1000)
# Make y
y = np.sqrt((.30*(1-.3))/(xx-1))
# Plot
plt.plot(xx, y)
While the other answer solves the issue, you should know that your attempt was not completely wrong. You can use plt.plot to plot individual points in a for loop. However, you will have to specify the marker in that case. This can be done using, let's say, a blue dot using bo as
for xx in range(10,100000,1000):
plt.plot(xx,math.sqrt((.30*(1-.3))/(xx-1)), 'bo')
Alternatively, in addition to the other answer, you can simply use plt.scatter even for a whole array as following. Note, in this case you will have to use the sqrt module from NumPy as you are performing vectorized operation here which is not possible with math.sqrt
xx = np.arange(10,100000,1000)
plt.scatter(xx,np.sqrt((.30*(1-.3))/(xx-1)), c='green', edgecolor='k')

Plotting a function in Python 2.7

I am trying to plot f in this program but I am screwing something up. Can someone have a look and inform me as to where I am messing up. Thanks.
import math
#x is the horizontal distance that the ball has traveled
g=9.81
v=raw_input('Enter an initial velocity:')
theta=raw_input('Enter the angle that the object was thrown at:')
y=raw_input('Enter the initial position of the object on the y-axis:')
t=(2*v*math.sin(theta))/g
x=(0.5)*((v*math.sin(theta))+v)*t
float(v)
float(theta)
float(y)
float(t)
f=x*math.tan(theta)-(1/(2*(v**2)))*((g(x**2))/(math.cos(theta)**2))+y
figure(1)
clf()
plot(f)
xlabel('x')
ylabel('y')
show()
So first of all, I would import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
Then, you have to convert your string input into floats, for that you can use eval.
initial_velo = eval(raw_input("Whatever you like: "))
...
Then for plotting with matplotlib you actually have to create a list of values (just as when you collect real data and then type it into the computer and then plot the single data points). For that I like to use linspace from the numpy import:
time_steps = np.linspace(0, t, steps)
# steps gives the numbers of intervals your time from 0 to t is splitted into
Now you create your functions x and f as functions of t. They will also have to be of type list. And in the end you can plot what you want via:
plt.figure(1)
plt.plot(time_steps, f)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
But maybe you should also watch how to plot stuff in the matplotlib doc. Also numpy has a great doc.

Python Pylab pcolor options for publication quality plots

I am trying to make DFT (discrete fourier transforms) plots using pcolor in python. I have previously been using Mathematica 8.0 to do this but I find that the colorbar in mathematica 8.0 has bad one-to-one correlation with the data I try to represent. For instance, here is the data that I am plotting:
[[0.,0.,0.10664,0.,0.,0.,0.0412719,0.,0.,0.],
[0.,0.351894,0.,0.17873,0.,0.,0.,0.,0.,0.],
[0.10663,0.,0.178183,0.,0.,0.,0.0405148,0.,0.,0.],
[0.,0.177586,0.,0.,0.,0.0500377,0.,0.,0.,0.],
[0.,0.,0.,0.,0.0588906,0.,0.,0.,0.,0.],
[0.,0.,0.,0.0493811,0.,0.,0.,0.,0.,0.],
[0.0397341,0.,0.0399249,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]]
So, its a lot of zeros or small numbers in a DFT matrix or small quantity of high frequency energies.
When I plot this using mathematica, this is the result:
The color bar is off and I thought I'd like to plot this with python instead.
My python code (that I hijacked from here) is:
from numpy import corrcoef, sum, log, arange
from numpy.random import rand
#from pylab import pcolor, show, colorbar, xticks, yticks
from pylab import *
data = np.array([[0.,0.,0.10664,0.,0.,0.,0.0412719,0.,0.,0.],
[0.,0.351894,0.,0.17873,0.,0.,0.,0.,0.,0.],
[0.10663,0.,0.178183,0.,0.,0.,0.0405148,0.,0.,0.],
[0.,0.177586,0.,0.,0.,0.0500377,0.,0.,0.,0.],
[0.,0.,0.,0.,0.0588906,0.,0.,0.,0.,0.],
[0.,0.,0.,0.0493811,0.,0.,0.,0.,0.,0.],
[0.0397341,0.,0.0399249,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]], np.float)
pcolor(data)
colorbar()
yticks(arange(0.5,10.5),range(0,10))
xticks(arange(0.5,10.5),range(0,10))
#show()
savefig('/home/mydir/foo.eps',figsize=(4,4),dpi=100)
And this python code plots as:
Now here is my question/list of questions:
I like how python plots this and would like to use this but...
How do I make all the "blue" which represents "0" go away like it does in my mathematica plot?
How do I rotate the plot to have the bright red spot in the top left corner?
The way I set the "dpi", is that correct?
Any useful references that I should use to strengthen my love for python?
I have looked through other questions on here and the user manual for numpy but found not much help.
I plan on publishing this data and it is rather important that I get all the bits and pieces right! :)
Edit:
Modified python code and resulting plot! What improvements would one suggest to this to make it publication worthy?
from numpy import corrcoef, sum, log, arange, save
from numpy.random import rand
from pylab import *
data = np.array([[0.,0.,0.10664,0.,0.,0.,0.0412719,0.,0.,0.],
[0.,0.351894,0.,0.17873,0.,0.,0.,0.,0.,0.],
[0.10663,0.,0.178183,0.,0.,0.,0.0405148,0.,0.,0.],
[0.,0.177586,0.,0.,0.,0.0500377,0.,0.,0.,0.],
[0.,0.,0.,0.,0.0588906,0.,0.,0.,0.,0.],
[0.,0.,0.,0.0493811,0.,0.,0.,0.,0.,0.],
[0.0397341,0.,0.0399249,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]], np.float)
v1 = abs(data).max()
v2 = abs(data).min()
pcolor(data, cmap="binary")
colorbar()
#xlabel("X", fontsize=12, fontweight="bold")
#ylabel("Y", fontsize=12, fontweight="bold")
xticks(arange(0.5,10.5),range(0,10),fontsize=19)
yticks(arange(0.5,10.5),range(0,10),fontsize=19)
axis([0,7,0,7])
#show()
savefig('/home/mydir/Desktop/py_dft.eps',figsize=(4,4),dpi=600)
The following will get you closer to what you want:
import matplotlib.pyplot as plt
plt.pcolor(data, cmap=plt.cm.OrRd)
plt.yticks(np.arange(0.5,10.5),range(0,10))
plt.xticks(np.arange(0.5,10.5),range(0,10))
plt.colorbar()
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal')
plt.show()
The list of available colormaps by default is here. You'll need one that starts out white.
If none of those suits your needs, you can try generating your own, start by looking at LinearSegmentedColormap.
Just for the record, in Mathematica 9.0:
GraphicsGrid#{{MatrixPlot[l,
ColorFunction -> (ColorData["TemperatureMap"][Rescale[#, {Min#l, Max#l}]] &),
ColorFunctionScaling -> False], BarLegend[{"TemperatureMap", {0, Max#l}}]}}

Categories