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')
Related
I am wondering whether I can plot a graph in which I show a range of best and worst results using matplotlib. The result should look something like this:
Image of the graph I want to replicate here.
You see the ranges around each point that specify what the best and worst measure is? This is exactly what I am looking for.
I'm pretty sure the errorbar function does exactly what you want:
https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.pyplot.errorbar.html
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
# yerr can be a single number or an array with same length as x and y
# depending on whether you want it to be constant or changing
yerr = 1
plt.errorbar(x, y, yerr=yerr)
plt.show()
I have a function with an histogram, plotted like this :
import matplotlib.pyplot as plt
import numpy as np
lin = np.linspace(min(foo), max(foo), len(foo))
plt.plot(lin, bar)
plt.hist(bar, density=True, bins=100, histtype='stepfilled', alpha=0.2)
plt.show()
Where foo and bar are simple arrays.
However, I would want to have the whole thing in a vertical way... I could add orientation='horizontal' to the histogram, but it would not change the function (and from what I have seen, there is nothing similar for a plot -> obviously it wouldn't be a function then, but a curve). Otherwise, I could add plt.gca().invert_yaxis() somewhere, but the same problem resides : plot is used for functions, so the swap of it does... well, that :
So, the only way I have now is to manually turn the whole original picture by 90 degrees, but then the axis are turned too and will no longer be on the left and bottom (obviously).
So, have you another idea ? Maybe I should try something else than plt.plot ?
EDIT : In the end, I would want something like the image below, but with axes made right.
If you have a plot of y vs x, you can swap axes by swapping arrays:
plt.plot(bar, lin)
There's no special feature because it's supported out of the box. As you've discovered, plotting a transposed histogram can be accomplished by passing in
orientation='horizontal'
I couldn't find any matplotlib method dealing with the issue. You can rotate the curve in a purely mathematical way, i.e. do it through the rotation matrix. In this simple case it is sufficient to just exchange variables x and y but in general it looks like this (let's take a parabola for a clear example):
rotation = lambda angle: np.array([[ np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
x = np.linspace(-10,10,1000)
y = -x**2
matrix = np.vstack([x,y]).T
rotated_matrix = matrix # rotation(np.deg2rad(90))
fig, ax = plt.subplots(1,2)
ax[0].plot(rotated_matrix[:,0], rotated_matrix[:,1])
ax[1].plot(x,y)
rotated_matrix = matrix # rotation(np.deg2rad(-45))
fig, ax = plt.subplots(1,2)
ax[0].plot(rotated_matrix[:,0], rotated_matrix[:,1])
ax[1].plot(x,y)
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)
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.
I wanted to create graphs for some math functions and tried to do this using matplotlib.I need to plot graphs of several functions in one plot sothat these can be compared against each other.
say these are the math functions
2**(math.log(x,2))
2**(2**(math.log(x,2)))
I tried this
from matplotlib.pyplot import plot as plt
x=arange(1000,1010)
y1=[2**(math.log(t,2)) for t in x ]
y2=[2**(2**(math.log(t,2))) for t in x ]
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()
this only shows one graph..that of (x,y2)
how do I make all the graphs show in one plot?
edit:
using plt.plot(x,y1,x,y2) produces this graph
I don't think they are going to be visible on the same scale. The first one is essentially y = x, y is about 1000. The second one is y = 2**x, and x starts at 1000...
However, plotting with log scale can help:
matplotlib.pyplot.yscale('log')