I'm trying to plot a cdf with matplotlib. However, cdfs begin in the origin, thus I prepended zeros to the x and y arrays. The problem is now that the origin now is marked as a data point. I'd like to remove that single marker in the point (0,0).
Code and picture below.
#Part of the myplot (my own) class
def cdf(self):
markers = ["x","v","o","^","8","s","p","+","D","*"]
for index,item in enumerate(np.asarray(self.data).transpose()):
x = np.sort(item)
y = np.arange(1,len(x)+1) / len(x)
x = np.insert(x,0,0)
y = np.insert(y,0,0)
self.plot = plt.plot(x,
y,
marker=markers[index],
label=self.legend[index])
self.setLabels( xlabel=self.xlabel,
ylabel="cumulative density",
title=self.title)
self.ax.set_ylim(ymax=1)
You cannot remove a marker. What you may do is to plot all the markers first, then append the origin and then plot a line.
x = np.sort(item)
y = np.arange(1,len(x)+1) / len(x)
self.plot, = plt.plot(x, y, marker=markers[index], ls="", label=self.legend[index])
x = np.insert(x,0,0)
y = np.insert(y,0,0)
self.plot2, = plt.plot(x, y, marker="", color=self.plot.get_color())
Alternative: Use the markevery argument.
x = np.sort(item)
y = np.arange(1,len(x)+1) / len(x)
x = np.insert(x,0,0)
y = np.insert(y,0,0)
markevery = range(1, len(x))
self.plot, = plt.plot(x, y, marker=markers[index], markevery=markevery,
ls="", label=self.legend[index])
Related
I am trying to use tricontourf to make a horizontal velocity contour plot for a metal rolling setup. Basically, the boundaries on the top and bottom of my horizontal velocity plot should be round but they are not because of tricontourf. Does anyone know how to fix this?
`
desired_quantity = "v_x"
x = df[["deformed_x"]].to_numpy()
x = np.transpose(x)
x = x.flatten()
y = df[["deformed_y"]].to_numpy()
y = np.transpose(y)
y = y.flatten()
z = df[[desired_quantity]].to_numpy()
z = np.transpose(z)
z = z.flatten()
y = y - y.min()
plt.figure(figsize=(12.6, 6))
levels = 18
plt.tricontourf(x, y, z, levels = levels)
plt.tricontourf(x, -1*y, z, levels = levels)
plt.colorbar()
plt.title(desired_quantity)
plt.show()`
I have a mathematical function
y = x^3 + sin(x) which I calculated using the below formular
np.random.seed(10)
x = np.random.random(20)
def calculate(x):
cube_x = np.power(x,3)
sin_x = np.sin(x)
y = cube_x + sin_x
return y
and I created a plot for the above equation
fig = plt.figure(figsize = (14, 8))
##Plot y = x^3 + sin(x)
y = calculate(x)
##plt.plot(x, y, 'b', label = '$x^3$ + $\sin$ $(x)$')
# Add features to our figure
plt.legend()
plt.grid(True, linestyle =':')
plt.xlim([0, 2])
plt.ylim([0, 2])
plt.title("Plot of y = $x^3$ + $\sin$ $(x)$ ")
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Show plot
plt.show()
I am not sure the above graph is correct. Please I need your assistance to know if I am getting the desired graph for the above function.
You should sort your random array in order to generate the plot correcty. You can use:
x = np.sort(np.random.random(20))
You can also use plt.scatter() instead of plt.plot(), so you don't have to sort the x array.
Like JMA said, you should to sort x first. If you had plotted your original data as a scatter, it would look fine:
However, if you were in a situation where you could not sort your input data prior to evaluating the function y, you can use np.argsort. Say you already have x and y computed and needed to sort x and y based on the order of x alone (e.g. y is not monotonic), you would use the following lines.
idx = np.argsort(x)
x, y = x[idx], y[idx]
and you plot would look like:
I'm trying to demonstrate a cost function right now and wondering if there's a way to traverse the parabola by adding plot in the same subplot and figure.
def costfuntion(b, a):
# b Value
x = np.linspace(b*(-b), b*(b), 100)
y = (x - a)**2
return y
My Plot Attempt:
plt.plot(costfuntion(20,5))
plt.ylabel("Cost Value");
#b = 'some b value'
plt.plot(b, marker='o', color='b')
What I'm trying to mimic
(Around: 1:13)
Since the y values depend on the a values you need to specify an a for the y lookup. Consider the following:
def costfunction(b, a):
# b Value
x = np.linspace(b*(-b), b*(b), 100)
y = (x - a)**2
return x, y
a = 5
c = costfunction(20, a)
plt.plot(c[0], c[1], linestyle='-', linewidth=1)
plt.ylabel("Cost Value");
b = 100
yb = (b - a)**2 # Find the corresponding y-value
plt.plot(b, yb, marker='o', color='b')
plt.show()
This will give you
You might also note that I modified the costfunction definition to return the x values, otherwise matplotlib will just use whatever values it pleases.
def costfuntion(b, a):
# b Value
x = np.linspace(b*(-b), b*(b), 100)
y = (x - a)**2
return x, y
x, y = costfuntion(20,5)
plt.plot(x, y)
for i in range(0, len(x), 2):
plt.plot(x[i], y[i], marker='o', color='b')
Change the cost function to return both x and y of the function you are plotting and use this information to plot points on the function.
I would like to have a 3d plot with matplotlib.
Data are the following: I have a matrix with each row containing Y coordinates for the 3d plot. Each row first elements are the X coordinates for the 3d plot. Finally, a second matrix contains high for each point, at a X,Y position. This second matrix thus contains my Z coordinates. Both matrices are arrays of arrays with Python. I would like to know how to transform data so as to obtain:
a plot of each 1d signal corresponding to an X, like this (photo available online)
a wireframe plot for same data, like this
I have written an helper function for a wireframe work,
######## HELPER FOR PLOT 3-D
def plot_3d(name,X,Y,Z):
fig = plt.figure(name)
ax = fig.gca(projection='3d')
X = np.array(X)
Y = np.array(Y)
Z = np.array(Z)
ax.plot_wireframe(X,Y,Z,rstride=10,cstride=10)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
plt.show()
but I dont know how to transform data X,Y,Z to make them fit requirements for matplotlib function, which want 2D lists for X, Y ,Z.
For first graph, I read help, and want to use 2d plot in 3d. Example source code gives:
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')
where z is the constant coordinate. In my case, x is the constant coordinate. I adapt with
fig = plt.figure('2d profiles')
ax = fig.gca(projection='3d')
for i in range(10):
x = pt ## this is a scalar
y = np.array(y)
z = np.array(z)
ax.plot(xs = x, y, z, xdir='x')
plt.show()
but there is warning: non-keyword arg after keyword arg. How to fix?
Thanks and regards
Regarding the display of a serie of vectors in 3D, I came with following 'almost working' solution:
def visualizeSignals(self, imin, imax):
times = self.time[imin:imax]
nrows = (int)((times[(len(times)-1)] - times[0])/self.mod) + 1
fig = plt.figure('2d profiles')
ax = fig.gca(projection='3d')
for i in range(nrows-1):
x = self.mat1[i][0] + self.mod * i
y = np.array(self.mat1T[i])
z = np.array(self.mat2[i])
ax.plot(y, z, zs = x, zdir='z')
plt.show()
As for 2D surface or meshgrid plot, I come through using meshgrid. Note that you can reproduce a meshgrid by yourself once you know how a meshgrid is built. For more info on meshgrid, I refer to this post.
Here is the code (cannot use it as such since it refers to class members, but you can build your code based on 3d plot methods from matplotlib I am using)
def visualize(self, imin, imax, typ_ = "wireframe"):
"""
3d plot signal between imin and imax
. typ_: type of plot, "wireframce", "surface"
"""
times = self.retT[imin:imax]
nrows = (int)((times[(len(times)-1)] - times[0])/self.mod) + 1
self.modulate(imin, imax)
fig = plt.figure('3d view')
ax = fig.gca(projection='3d')
x = []
for i in range(nrows):
x.append(self.matRetT[i][0] + self.mod * i)
y = []
for i in range(len(self.matRetT[0])):
y.append(self.matRetT[0][i])
y = y[:-1]
X,Y = np.meshgrid(x,y)
z = [tuple(self.matGC2D[i]) for i in range(len(self.matGC))] # matGC a matrix
zzip = zip(*z)
for i in range(len(z)):
print len(z[i])
if(typ_ == "wireframe"):
ax.plot_wireframe(X,Y,zzip)
plt.show()
elif(typ_ == "contour"):
cset = ax.contour(X, Y, zzip, zdir='z', offset=0)
plt.show()
elif(typ_ == "surf_contours"):
surf = ax.plot_surface(X, Y, zzip, rstride=1, cstride=1, alpha=0.3)
cset = ax.contour(X, Y, zzip, zdir='z', offset=-40)
cset = ax.contour(X, Y, zzip, zdir='x', offset=-40)
cset = ax.contour(X, Y, zzip, zdir='y', offset=-40)
plt.show()
Given a function g(x), I want to find a fixed point to this function using
fixed point iteration. Except for finding the point itself, I want to plot the graph to the function using matplotlib.pyplot, and include the vertical and horizontal bars that show how the iteration closes in on the fixed point (if one exists). Example picture
All help appreciated!
/programming newbie
EDIT: Since I'm no too comfortable with generator objects yet, I've written the following code. It doesn't quite work though: what's wrong with it?
from matlibplot.axes import vlines, hlines
def fixpt(f, x, epsilon=1.0E-4, N=500, store=False):
y = f(x)
n = 0
if store: Values = [(x, y)]
while abs(y-x) >= epsilon and n < N:
x = f(x)
n += 1
y = f(x)
if store: Values.append((x, y))
vlines(x, min(x, y), max(x, y), color='b')
hlines(y, min(y, x), max(y, x), color='b')
if store:
return y, Values
else:
if n >= N:
return "No fixed point for given start value"
else:
return x, n, y
def fixedpoint(f,x):
while x != f(x):
yield x
x = f(x)
yield x
Usage: fixedpoint(g,some_starting_value).
Vertical and horizontal bars depend on plotting library. Specify which one you use.
Your function looks fine. I am not familiar with vlines and hlines. I used your store arg to get the points, and plot them outside the function (it is generally better to separate problems like this).
I used only the plot function from matplotlib.pyplot, and the show function to display the graph.
from matplotlib import pyplot as plt
import numpy as np
def fixpt(f, x, epsilon=1.0E-4, N=500, store=False):
y = f(x)
n = 0
if store: Values = [(x, y)]
while abs(y-x) >= epsilon and n < N:
x = f(x)
n += 1
y = f(x)
if store: Values.append((x, y))
if store:
return y, Values
else:
if n >= N:
return "No fixed point for given start value"
else:
return x, n, y
# define f
def f(x):
return 0.2*x*x
# find fixed point
res, points = fixpt(f, 3, store = True)
# create mesh for plots
xx = np.arange(0, 6, 0.1)
#plot function and identity
plt.plot(xx, f(xx), 'b')
plt.plot(xx, xx, 'r')
# plot lines
for x, y in points:
plt.plot([x, x], [x, y], 'g')
plt.plot([x, y], [y, y], 'g')
# show result
plt.show()
Here is how I thought it through :
from pylab import *
def f(x):
return 8*x/(1 + 2*x)
def cobweb(x0, n, ax):
xs = [x0]
ys = [0]
for i in range(1,n):
if i % 2 == 0:
xs.append(ys[-1])
ys.append(ys[-1])
else:
xs.append(xs[-1])
ys.append(f(xs[-1]))
ax.plot(xs, ys, 'k--', lw=2.0)
x = linspace(0, 4, 100)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, x, 'k', lw=2.0)
ax.plot(x, f(x), 'r', lw=2.0)
cobweb(0.5, 50, ax)
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$f(x)$')
grid()
show()