Related
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 ^^
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!
I am trying to draw histogram but nothing appears in the Figure Window.
My code is below:
import numpy as np
import matplotlib.pyplot as plt
values = [1000000, 1525097, 2050194, 1095638, 1620736, 2145833, 1191277, 1716375, 1286916, 1382555]
plt.hist(values, 10, histtype = 'bar', facecolor = 'blue')
plt.ylabel("Values")
plt.xlabel("Bin Number")
plt.title("Histogram")
plt.axis([0,11,0,220000])
plt.show()
This is the output:
I am trying to achieve this plot
Any help would be much appreciated...
You are confusing what a histogram is. The histogram that can be produced with the given data is as given below.
A histogram basically counts how many given values fall within a given range.
You have given incorrect arguments to the axis() function. The ending value is 2200000 You missed a single zero. Also you have swapped the arguments. Limits of the x axis comes first and then the limits of the Y axis. This is the modified code:
import numpy as np
import matplotlib.pyplot as plt
values = [1000000, 1525097, 2050194, 1095638, 1620736, 2145833, 1191277, 1716375, 1286916, 1382555]
plt.hist(values, 10, histtype = 'bar', facecolor = 'blue')
plt.ylabel("Values")
plt.xlabel("Bin Number")
plt.title("Histogram")
plt.axis([0,2200000,0,11])
plt.show()
This is the histogram generated:
I finally achieved it...
Here is the code:
import numpy as np
import matplotlib.pyplot as plt
values = [1000000, 1525097, 2050194, 1095638, 1620736, 2145833, 1191277, 1716375, 1286916, 1382555]
strategy = [1,2,3,4,5,6,7,8,9,10]
value = np.array(values)
strategies = np.array(strategy)
plt.bar(strategy, values, .8)
plt.ylabel("Values")
plt.xlabel("Bin Number")
plt.title("Histogram")
plt.axis([1,11,0,2200000])
plt.show()
Output:
How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say jet)? I tried a couple of different approaches here and I think I'm stumped. values[] is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the arrays have the same length.
fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
retLine, = ax.plot(line, color=colorVal)
#retLine.set_color()
lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()
The error you are receiving is due to how you define jet. You are creating the base class Colormap with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.
What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.
This is an updated version of your example:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)
fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
colorText = (
'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
)
retLine, = ax.plot(line,
color=colorVal,
label=colorText)
lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()
Resulting in:
Using a ScalarMappable is an improvement over the approach presented in my related answer:
creating over 20 unique legend colors using matplotlib
I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy import linspace
start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines)
colors = [ cm.jet(x) for x in cm_subsection ]
for i, color in enumerate(colors):
plt.axhline(i, color=color)
plt.ylabel('Line Number')
plt.show()
This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.
Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.
So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:
colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]
In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:
>>> from matplotlib import cm
>>> dir(cm)
A combination of line styles, markers, and qualitative colors from matplotlib:
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
UPDATE: Supporting not only ListedColormap, but also LinearSegmentedColormap
import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})
U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.
Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.
from matplotlib.pyplot import cm
import numpy as np
#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:
color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
ax1.plot(x, y,c=c)
#or version 2: - faster and better:
color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)
#or version 3:
color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
c=next(color)
ax1.plot(x, y,c=c)
example of 3:
Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44
I would like to plot an EPSgram (see below) using Python and Matplotlib.
The boxplot function only plots quartiles (0, 25, 50, 75, 100). So, how can I add two more boxes?
I put together a sample, if you're still curious. It uses scipy.stats.scoreatpercentile, but you may be getting those numbers from elsewhere:
from random import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import scoreatpercentile
x = np.array([random() for x in xrange(100)])
# percentiles of interest
perc = [min(x), scoreatpercentile(x,10), scoreatpercentile(x,25),
scoreatpercentile(x,50), scoreatpercentile(x,75),
scoreatpercentile(x,90), max(x)]
midpoint = 0 # time-series time
fig = plt.figure()
ax = fig.add_subplot(111)
# min/max
ax.broken_barh([(midpoint-.01,.02)], (perc[0], perc[1]-perc[0]))
ax.broken_barh([(midpoint-.01,.02)], (perc[5], perc[6]-perc[5]))
# 10/90
ax.broken_barh([(midpoint-.1,.2)], (perc[1], perc[2]-perc[1]))
ax.broken_barh([(midpoint-.1,.2)], (perc[4], perc[5]-perc[4]))
# 25/75
ax.broken_barh([(midpoint-.4,.8)], (perc[2], perc[3]-perc[2]))
ax.broken_barh([(midpoint-.4,.8)], (perc[3], perc[4]-perc[3]))
ax.set_ylim(-0.5,1.5)
ax.set_xlim(-10,10)
ax.set_yticks([0,0.5,1])
ax.grid(True)
plt.show()