I am not able to display graph in matplotlib - python

I'm trying to print a logistic differential equation and I'm pretty sure the equation is written correctly but my graph doesn't display anything.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
for num in range(len(xList)-1):
plt.plot(xList[num], eq(con,x))
x=eq(con,x)
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show()

You get nothing in your plot because you are plotting points.
In plt you need to have x array and y array (that have the same length) in order to make a plot.
If you want to do exactly what you are doing I suggest to do like this:
import matplotlyb.pyplot as plt # just plt is sufficent
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
y = np.zeros(len(xList)) # initialize an array with the same lenght as xList
for num in range(len(xList)-1):
y[num] = eq(con,x)
x=eq(con,x)
plt.figure() # A good habit is always to use figures in plt
plt.plot(xList, y) # 2 arrays of the same lenght
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show() # now you should get somthing here
I hope that this helps you ^^

Related

how to plot some lists with different shape?

I have some lists that each of which has a different shape and I would like to plot all of them together in one polar scatter plot. I also tried to use iter tools but I could not find the solution.
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,56,7,8]
ax1 = plt.subplot(111,polar= True)
for i in range (0,3):
theta = 4 * np.pi * np.random.rand(len(a[i]))
ax1.set_ylim(0,0.1)
ax1.set_rlabel_position(180)
for i in range (0,3):
ax1.scatter(theta,a[i], cmap='hsv', alpha=0.5)
Be carefull i modified your lists for a better visual exmaple!
I hope I understood your question correctly...
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,7,7,8]
ax1 = plt.subplot(111,polar= True)
for onelist in [a1,a2,a3,a4]:
theta_list = np.linspace(0,2*np.pi,len(onelist))
ax1.plot(theta_list,onelist,marker="x")
plt.show()

How to plot coordinates (1,2) against time (0.5) in python

I am trying to plot vehicle position (coordinates - x,y) against time(1s,2s,3s...). I tried with matplotlib but could not succeed. I am new in python. Could anyone help me please.
My code:
import matplotlib.pyplot as plt
import numpy as np
coordinate = [[524.447876,1399.091919], [525.1377563,1399.95105], [525.7932739,1400.767578], [526.4627686,1401.601563],
[527.2360229,1402.564575], [527.8989258,1403.390381], [528.5689697,1404.224854]]
timestamp =[0,0.05,0.1,0.15,0.2,0.25,0.3]
plt.plot(coordinate,timestamp)
Plot comes like: But this is wrong one. I did wrong.
Plot supposed to become, in particular, timestamp (1s) the vehicle position is (x,y). So there should be one line just like vehicle trajectory.
Thanks.
I believe this is the output you're looking for:
import matplotlib.pyplot as plt
import numpy as np
coordinate = [[524.447876,1399.091919],
[525.1377563,1399.95105],
[525.7932739,1400.767578],
[526.4627686,1401.601563],
[527.2360229,1402.564575],
[527.8989258,1403.390381],
[528.5689697,1404.224854]]
v1 = [y[1] for y in coordinate]
v2 = [y[0] for y in coordinate]
x = [0,0.05,0.1,0.15,0.2,0.25,0.3]
plt.plot(x,v1)
plt.plot(x,v2,'--')
plt.ylim(0,1500)
plt.show()
Does something simple like this meet your needs:
import matplotlib.pyplot as plt
coordinates = [
(524.447876,1399.091919),
(525.1377563,1399.95105),
(525.7932739,1400.767578),
(526.4627686,1401.601563),
(527.2360229,1402.564575),
(527.8989258,1403.390381),
(528.5689697,1404.224854),
]
timestamp = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3]
x, y = zip(*coordinates)
ax = plt.axes(projection="3d")
ax.plot(x, y, timestamp);
plt.show()
Matplotlib will let you rotate the image with the mouse to view it from various angles.
Hi I think the problem over here is that you are using a two-dimensional list, so matplotlib plots the coordinates and not the timestamp.
Code:
import matplotlib.pyplot as plt
import numpy as np
coordinate = np.array([[524.447876,1399.091919], [525.1377563,1399.95105], [525.7932739,1400.767578], [526.4627686,1401.601563], [527.2360229,1402.564575], [527.8989258,1403.390381], [528.5689697,1404.224854]])
timestamp =np.array([0,0.05,0.1,0.15,0.2,0.25,0.3])
plt.plot(coordinate)
Output:
You have to convert it into a single dimension list like this:
coordinate_new = np.array([524.447876,525.1377563,1399.95105, 525.7932739,1400.767578, 526.4627686,1401.601563])
timestamp =np.array([0,0.05,0.1,0.15,0.2,0.25,0.3])
plt.plot(coordinate_new, timestamp)
Then the output will be:
Hope I could help!!
If you want to plot it in 3-d, here is what you can do:
import matplotlib.pyplot as plt
#importing matplotlib
fig = plt.figure() #adding figure
ax_3d = plt.axes(projection="3d") #addign 3-d axes
coordinate_x = [524.447876, 525.137756, 525.7932739, 526.4627686, 527.2360229, 527.8989258, 528.5689697]
coordinate_y = [1399.091919, 1399.95105,1400.767578,1401.601563,1402.564575,1403.390381,1404.224854]
timestamp =[0,0.05,0.1,0.15,0.2,0.25,0.3]
# defining the variables
ax.plot(coordinate_x, coordinate_y, timestamp)
#plotting them
Output:
All the Best!

Plotting a 3D quiver plot and ode

I am trying to do a 3D quiver plot and combining it with odeint to solve a linearized equation. Basically, I want something similar to this but in 3D. The particular issue I am having is that near the end of the code, when I am doing the ax.quiver() plot, I keep getting the error that "val must be a float or nonzero sequence of floats", and I am unsure how to resolve it.
from scipy.integrate import odeint
from numpy import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax =fig.add_subplot(1, 1, 1, projection='3d')
ax.set_xlabel('x')
ax.set_ylabel('u')
ax.set_zlabel('u1')
def testplot(X, t=0,c=0.2):
x = X[0]
u = X[1]
u1=X[2]
dxdt =x**2*(-1+x+u)*(1-x+(-1+c)*u**2)
du1dt =c**2*u*(2+x*(-4+2.25*x)+(-4 + 4*x)*u**2 + 2*u**4 + x**2*u*u1)
dudt=u1*dxdt
return [dxdt, dudt,du1dt]
X0 = [0.01,0.995,-0.01]#initial values
t = linspace(0, 50, 250)
c=[0.2,0.5,1,2]#changing parameter
for m in c:
sol = odeint(testplot,X0,t,mxstep=5000000,args=(m,))#solve ode
ax.plot(sol[:,0],sol[:,1],sol[:,2],lw=1.5,label=r'$c=%.1f$'%m)
x = linspace(-3,3,15)
y = linspace(-4,4,15)
z= linspace(-2,2,15)
x,y,z = meshgrid(x,y,z) #create grid
X,Y,Z = testplot([x,y,z])
M = sqrt(X**2+Y**2+Z**2)#magnitude
M[M==0]=1.
X,Y,Z = X/M, Y/M, Z/M
ax.quiver(x,y,z,X,Y,Z,M,cmap=plt.cm.jet)
ax.minorticks_on()
ax.legend(handletextpad=0,loc='upper left')
setp(ax.get_legend().get_texts(),fontsize=12)
fig.savefig("testplot.svg",bbox_inches="tight",\
pad_inches=.15)
Looks like you have an extra argument in ax.quiver(). From what I can tell, it looks like "M" is the extra argument. Taking that out, your quiver call looks like:
ax.quiver(x,y,z,X,Y,Z,cmap=plt.cm.jet)
The resulting image looks like:

pyplot: loglog() with base e

Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:
import matplotlib.pyplot as pyplot
import math
e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)
Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...
Any advice is greatly appreciated!
When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.
From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)
import numpy as np
import matplotlib.pyplot as plt
# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e
plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()
Edit
Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x = np.linspace(1, 4, 1000)
y = x**3
fig, ax = plt.subplots()
ax.loglog(x,y, basex=np.e, basey=np.e)
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
It can also works for semilogx and semilogy to show them in e and also change their name.
import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
Take a look at the image.

How to make the histograms 'touch' in pylab?

So I made a program that does what I need, mainly plots histogram from my data, but I have a few issues with it:
Here's the program:
# -*- coding: cp1250 -*-
from __future__ import division
from numpy import *
from matplotlib import rc
from matplotlib.pyplot import *
import numpy as np
import matplotlib.pyplot as plt
data = loadtxt("mioni.txt", int)
nuz = len(data)
nsmp = 20
duz = int(nuz/nsmp)
L = []
for i1 in range(0,nsmp):
suma = 0
for i2 in range(0,duz):
suma += data[i1*duz+i2]
L.append(suma)
print L
plt.hist(L, 20, normed=1, facecolor='blue', alpha=0.75)
plt.xlabel('t(\mu s)')
plt.ylabel('Broj događaja')
plt.axis([0,10,0,300])
plt.grid(True)
plt.show()
EDIT: so I managed to deal with the ugly sums, but now my histograms don't work :(
Data is here: http://dropcanvas.com/kqjem
What's wrong? I get tons of errors and python crashes :\
The problem comes from having a discrete data set, it looks like you set the bins parameter to something that doesn't fit. Use the pylab.hist parameter histtype="stepfilled" to get them to touch without the lines. Here are a few examples:
import numpy as np
import pylab as plt
# Sample data
X1 = np.random.exponential(1.0,size=5000)
X2 = [int(z) for z in X1]
plt.subplot(221)
plt.hist(X1,bins=50)
plt.title('Continuous Data')
plt.subplot(222)
plt.hist(X2,bins=50)
plt.title('Discrete Data')
plt.subplot(223)
plt.hist(X2,histtype='stepfilled')
plt.title('Discrete Data Filled')
plt.show()
use numpy.histogram: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
or matplotlib.pyplot.hist: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
for example:
plt.hist(data, bins=20)

Categories