This is my code. I want to get a typical sine graph but somehow am not getting it.
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,2*(np.pi),(np.pi)/2)
y=np.sin(x)
plt.plot(x,y,color='b')
plt.show()
I am getting this graph.
1
Also, what would I need to modify to the axes so that it would look like this ?
2
Look at the step size in your range:
x=np.arange(0,2*(np.pi),(np.pi)/2)
You're evaluating sin every pi/2 ... in other words, only at -1, 0 and 1.
You need a much smaller step size ... say, np.pi / 100
For future problems, see this lovely reference for debugging help. Simply printing x would have shown your problem.
Related
I have 4 known points that I am trying to run a smooth curve through.
gg_xy=np.array([[-2.612,0],[0,1.6969999999999996],[0.5870000000000001,0],[0,-2.605]])
plt.plot(gg_xy[:,0],gg_xy[:,1],'ro')
ggx,ggy=splprep(gg_xy.T,u=None,s=0.0,per=1)
gg_xspline=np.linspace(ggy.min(),ggy.max(),300)
ggxnew,ggynew=splev(gg_xspline,ggx,der=0)
plt.plot(ggxnew,ggynew)
plt.show()
This is my ouput:
It is missing a point when interpolating. Could someone help me force it through this point? Is there a better way to do this other than using spline interpolation? Edit: the curve must be a single connected loop.
Thanks!
from scipy.interpolate import splprep, splev
import matplotlib.pyplot as plt
import numpy as np
gg_xy=np.array([[-2.612,0],[0,1.6969999999999996],
[0.5870000000000001,0],[0,-2.605], [0,-2.605]])
plt.plot(gg_xy[:,0],gg_xy[:,1],'ro')
ggx,ggy=splprep(gg_xy.T,u=None,s=0.0,per=1)
gg_xspline=np.linspace(ggy.min(),ggy.max(),300)
ggxnew,ggynew=splev(gg_xspline,ggx,der=0)
plt.plot(ggxnew,ggynew)
plt.show()
Docs:
per: int, optional
If non-zero, data points are considered periodic with
period x[m-1] - x[0] and a smooth periodic spline approximation is
returned. Values of y[m-1] and w[m-1] are not used.
Looks like it ignores the last point, so I just repeated the last point.
I am a relative beginner when it comes to python, and I currently am trying to figure out some python for a problem I have.
I am attempting to calculate the lyapunov exponent of a bifurcation diagram I am supposed to be creating.
The equation is X_(n+1) = asin(pi x_(n)),
where a = 0.9 (for when I calculate the exponent)
This is currently the code that i have set up to create an array of values becoming large.
import numpy as np
np.set_printoptions(threshold=np.nan)
import matplotlib.pyplot as plt
a = np.linspace(0,1)
xn = np.array([.001], dtype = float)
for i in range(0,10000):
y = a*np.sin(np.pi*xn[i])
xn = np.append(xn,y)
plt.plot(a,xn[-1])
However, very obviously, when i plot xn, i just get a mad mess of dots instead of a bifurcation diagram. I was hoping I could get some guidance as to moving towards the correct diagram which i can hopefully use to get closer to my end goal.
Thanks for any help, I appreciate it!
I'm not exactly sure what you are trying to accomplish, and I don't know enough about bifurcations to really figure it out on my own, but I was able to get something that seems to work. The main caveat seems to be that if alpha starts at less than 0.158, it won't produce the right output.
import numpy as np
import matplotlib.pyplot as plt
x = [0.001]
a = np.linspace(0.2,1,100000)
for i in range(1,a.shape[0]):
x.append(a[i]*np.sin(np.pi*x[i-1]))
fig = plt.figure(figsize=(8,4))
plt.scatter(a,x,s=0.1)
which produces the figure:
Given 2000 random points in a unit circle (using numpy.random.normal(0,1)), I want to normalize them such that the output is a circle, how do I do that?
I was requested to show my efforts. This is part of a larger question: Write a program that samples 2000 points uniformly from the circumference of a unit circle. Plot and show it is indeed picked from the circumference. To generate a point (x,y) from the circumference, sample (x,y) from std normal distribution and normalise them.
I'm almost certain my code isn't correct, but this is where I am up to. Any advice would be helpful.
This is the new updated code, but it still doesn't seem to be working.
import numpy as np
import matplotlib.pyplot as plot
def plot():
xy = np.random.normal(0,1,(2000,2))
for i in range(2000):
s=np.linalg.norm(xy[i,])
xy[i,]=xy[i,]/s
plot.plot(xy)
plot.show()
I think the problem is in
plot.plot(xy)
even if I use
plot.plot(xy[:,0],xy[:,1])
it doesn't work.
Connected lines are not a good visualization here. You essentially connect random points on the circle. Since you do this quite often, you will get a filled circle. Try drawing points instead.
Also avoid name space mangling. You import matplotlib.pyplot as plot and also name your function plot. This will lead to name conflicts.
import numpy as np
import matplotlib.pyplot as plt
def plot():
xy = np.random.normal(0,1,(2000,2))
for i in range(2000):
s=np.linalg.norm(xy[i,])
xy[i,]=xy[i,]/s
fig, ax = plt.subplots(figsize=(5,5))
# scatter draws dots instead of lines
ax.scatter(xy[:,0], xy[:,1])
If you use dots instead, you will see that your points indeed lie on the unit circle.
Your code has many problems:
Why using np.random.normal (a gaussian distribution) when the problem text is about uniform (flat) sampling?
To pick points on a circle you need to correlate x and y; i.e. randomly sampling x and y will not give a point on the circle as x**2+y**2 must be 1 (for example for the unit circle centered in (x=0, y=0)).
A couple of ways to get the second point is to either "project" a random point from [-1...1]x[-1...1] on the unit circle or to pick instead uniformly the angle and compute a point on that angle on the circle.
First of all, if you look at the documentation for numpy.random.normal (and, by the way, you could just use numpy.random.randn), it takes an optional size parameter, which lets you create as large of an array as you'd like. You can use this to get a large number of values at once. For example: xy = numpy.random.normal(0,1,(2000,2)) will give you all the values that you need.
At that point, you need to normalize them such that xy[:,0]**2 + xy[:,1]**2 == 1. This should be relatively trivial after computing what xy[:,0]**2 + xy[:,1]**2 is. Simply using norm on each dimension separately isn't going to work.
Usual boilerplate
import numpy as np
import matplotlib.pyplot as plt
generate the random sample with two rows, so that it's more convenient to refer to x's and y's
xy = np.random.normal(0,1,(2,2000))
normalize the random sample using a library function to compute the norm, axis=0 means consider the subarrays obtained varying the first array index, the result is a (2000) shaped array that can be broadcasted to xy /= to have points with unit norm, hence lying on the unit circle
xy /= np.linalg.norm(xy, axis=0)
Eventually, the plot... here the key is the add_subplot() method, and in particular the keyword argument aspect='equal' that requires that the scale from user units to output units it's the same for both axes
plt.figure().add_subplot(111, aspect='equal').scatter(xy[0], xy[1])
pt.show()
to have
I'm making a demonstration of a different types of regression in numpy with ipython, and so far, I've been able to plot a simple linear regression without difficulty. Now, when I go on to make a quadratic fit to my data and go to plot it, I don't get a quadratic curve but instead get many lines. Here's the code I'm running that generates the problem:
import numpy
from numpy import random
from matplotlib import pyplot as plt
import math
# Generate random data
X = random.random((100,1))
epsilon=random.randn(100,1)
f = 3+5*X+epsilon
# least squares system
A =numpy.array([numpy.ones((100,1)),X,X**2])
A = numpy.squeeze(A)
A = A.T
quadfit = numpy.linalg.solve(numpy.dot(A.transpose(),A),numpy.dot(A.transpose(),f))
# plot the data and the fitted parabola
qdbeta0,qdbeta1,qdbeta2 = quadfit[0][0],quadfit[1][0],quadfit[2][0]
plt.scatter(X,f)
plt.plot(X,qdbeta0+qdbeta1*X+qdbeta2*X**2)
plt.show()
What I get is this picture (zoomed in to show the problem):
You can see that rather than having a single parabola that fits the data, I have a huge number of individual lines doing something that I'm not sure of. Any help would be greatly appreciated.
Your X is ordered randomly, so it's not a good set of x values to use to draw one continuous line, because it has to double back on itself. You could sort it, I guess, but TBH I'd just make a new array of x coordinates and use those:
plt.scatter(X,f)
x = np.linspace(0, 1, 1000)
plt.plot(x,qdbeta0+qdbeta1*x+qdbeta2*x**2)
gives me
I have some spatially-distributed data. I'm plotting this with matplotlib.pyplot.hexbin and would like to change the "background" (i.e. zero-value) colour. An example is shown below - my colour-map of choice is matplotlib.cm.jet:
How can I change the base colour from blue to white? I have done something similar with masked arrays when using pcolormesh, but I can't see anyway of doing so in the hexbin arguments. My instinct would be to edit the colourmap itself, but I've not had much experience with that.
I'm using matplotlib v.0.99.1.1
hexbin(x,y,mincnt=1) should do the trick. Essentially, you only want to display the hexagons with more than 1 count in them.
from numpy import linspace
from numpy.random import normal
from pylab import hexbin,show
n = 2**6
x = linspace(-1,1,n)
y = normal(0,1,n)
h = hexbin(x,y,gridsize=10,mincnt=0)
gives,
and h = hexbin(x,y,gridsize=10,mincnt=1) gives,