I would like to fill the area between the curve y1=x^3 and then line y2=3x-2.
Below is code I have that will do this, however, I want to place the restriction that y1 < y2 (which I have done with the where option of fill_between) and that x<1.
The problem that occurs with the code below is that the area between the curve is filled for x>1. I would like to plot these graphs on the range [-2.5,2.5]. How do I get matplotlib to stop filling between the curves for x>1?
My code:
import matplotlib.pyplot as plot
import numpy as np
x = np.linspace(-2.5, 2.5, 100)
y1 = np.array([i**3 for i in x])
y2 = np.array([3*i-2 for i in x])
fig = plot.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x, y1, label=r"$y=x^3$")
ax.plot(x, y2, label=r"$y=3x-2$")
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.fill_between(x, y1, y2, where=y2<y1, facecolor='green')
ax.legend()
plot.show()
I got it. The easiest fix is to define 3 new variables, u,v, and w, where u holds the x values for v and w, and v = x^3, w=3x-2.
u=x[x<1]
v=y1[y1<1]
w=y2[y2<1]
Then plot these values with fill_between:
ax.fill_between(u, v, w, where=w<v, facecolor='green')
Related
I have a list and i want to plot the list in such a way that for certain range of x axis the lines are dotted while for other range it is solid.
e.g.:
y=[11,22,33,44,55,66,77,88,99,100]
x=[1,2,3,4,5,6,7,8,9,10]
i did this:
if i range(4,8):
plt.plot(x,y,marker='D')
else :
plt.plot(x,y,'--')
plt.show()
but this doesnot work.
can someone help?
Slice the data into 3 intervals
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
x = [1,2,3,4,5,6,7,8,9,10]
y = [11,22,33,44,55,66,77,88,99,100]
fig, ax = plt.subplots()
m, n = 4, 8
x1, x2, x3 = x[:m+1], x[m:n+1], x[n:]
y1, y2, y3 = y[:m+1], y[m:n+1], y[n:]
ax.plot(x1, y1, color='red', linestyle='solid', marker='D')
ax.plot(x2, y2, color='blue', linestyle='dashed')
ax.plot(x3, y3, color='red', linestyle='solid', marker='D')
plt.show()
Here is a solution with the same colours for the whole line:
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9,10]
y = [11,22,33,44,55,66,77,88,99,100]
fig, ax = plt.subplots()
x1, y1 = x[:4], y[:4]
x2, y2 = x[3:8], y[3:8]
x3, y3 = x[7:], y[7:]
ax.plot(x1, y1, marker='D', color='b')
ax.plot(x2, y2, '--', color='b')
ax.plot(x3, y3, marker='D', color='b')
Change line characteristics based on the value of x:
import numpy as np
from matplotlib import pyplot as plt
Make arrays of the lists;
y = np.array([11,22,33,44,55,66,77,88,99,100])
x = np.array([1,2,3,4,5,6,7,8,9,10])
make a boolean array based on your condition(s);
dashed = np.logical_or(x<4,x>=8)
use the boolean array to filter the data when you plot.
plt.plot(x[~dashed],y[~dashed],color='blue',marker='D')
plt.plot(x[dashed],y[dashed],color='blue',ls='--')
I am trying to plot three planes in 3D space with Matplotlib.
What I got so far looks not good, and I want to ask.
Is there a better solution, so they are intersected?
x = np.linspace(-5,5,2)
y = np.linspace(-5,5,2)
z = np.linspace(-5,5,2)
X,Z = np.meshgrid(x,z)
Y1 = -2*X
Y2 = (-1+X+Z)/2
Y3 = -(4-4*z)/3
# plot the surface
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_surface(X, Y1, Z, alpha=0.5)
ax.plot_surface(X, Y2, Z, alpha=0.5)
ax.plot_surface(X, Y3, Z, alpha=0.5)
plt.show()
Say I want to inset a plot to a figure, but the inset plot has different axis range than the one I am marking the inset to. For example:
fig, ax = plt.subplots()
axins = inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)
x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)
x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
axins.set_xlim(x1, x2) # apply the x-limits
axins.set_ylim(y1, y2) # apply the y-limits
plt.xticks(visible=False)
plt.yticks(visible=False)
mark_inset(ax, axins, loc1=4, loc2=1)#, fc="none")#, ec="0.5")
The result is an empty inset plot:
But this is obvious, since I set the limits of x and y to ranges where x**3 does not pass.
What I want to see is, for example, a plot of x**3 for 0 to 1 in the inset plot, while the mark_inset will still 'zoom' to the region boxed above, which is of different range.
How can I do this?
In that case you cannot use mark_inset directly, because that is exactly what this function does: synchronizing the marker with the axes limits of the inset.
Using a rectangle
Instead you may position some rectangle whereever you want it to be and use ConnectionPatches to draw some lines in between the inset and the rectangle.
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il
import matplotlib.patches as mpatches
fig, ax = plt.subplots()
axins = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)
x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)
x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
rect = mpatches.Rectangle((x1,y1), width=x2-x1, height=y2-y1, facecolor="None", edgecolor="k", linewidth=0.8)
fig.canvas.draw()
p1 = mpatches.ConnectionPatch(xyA=(1,0), xyB=(x2,y1), coordsA="axes fraction", coordsB="data", axesA=axins, axesB=ax)
p2 = mpatches.ConnectionPatch(xyA=(1,1), xyB=(x2,y2), coordsA="axes fraction", coordsB="data", axesA=axins, axesB=ax)
ax.add_patch(rect)
ax.add_patch(p1)
ax.add_patch(p2)
plt.show()
Use dummy axes
You may also simply add an additional inset, just for the purpose of using mark_inset with it.
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il
fig, ax = plt.subplots()
axins_dummy = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)
axins = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)
x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)
x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
axins_dummy .set_xlim(x1, x2) # apply the x-limits
axins_dummy .set_ylim(y1, y2) # apply the y-limits
axins_dummy.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False )
il.mark_inset(ax,axins_dummy , loc1=4, loc2=1)#, fc="none")#, ec="0.5")
plt.show()
In both cases, the resulting plot would look like
Maybe it's worth noting that the resulting graph is of course incorrect. Any reader would assume that the inset shows part of the curve, which is not the case. Hence make sure not to use such graph in a publication or report.
I would like to add 3D plot in matplotlib 1.5.1 to the existing set of 2D plots (subplots). 2D plots work fine w/o 3D, but when I add 3D I'm getting an error that 'module' object has no attribute 'plot_surface'. I'd like to keep the code simple so I apply all commands to plt without creating new figure(there is also a way of adding labels with set_xlabel) which makes things ambiguous. The first 3 plots are simple 2D plots and the last is 3D.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
y1 = u.nodes.concentration
x1 = u.nodes.x
plt.figure(figsize=(20, 10))
plt.subplot(221)
plt.title('Profile')
plt.xlabel('Range')
plt.ylabel('Concentration')
plt.plot(x1, y1, '-b')
# Inhibitor plt
y2 = z.nodes.concentration
x2 = z.nodes.x
plt.subplot(222)
plt.title('Profile')
plt.xlabel('Range')
plt.ylabel('Concentration')
plt.plot(x2, y2, '-r')
# Modulator plt
y3 = v.nodes.concentration
x3 = v.nodes.x
plt.subplot(223)
plt.title('Profile')
plt.xlabel('Range')
plt.ylabel('Concentration')
plt.plot(x3, y3, '-g')
#3D plot
plt.subplot(224, projection='3d')
# Grab data.
xx = u_fft_x_norm
yy = [i*time_period for i in xrange(1, times)]
zz = u_timespace
XX, YY = np.meshgrid(xx, yy)
ZZ = zz
# Plot a basic wireframe.
plt.plot_surface(XX, YY, ZZ, rstride=20, cstride=20)
plt.xlabel('Space')
plt.ylabel('Time')
plt.zlabel('Value')
plt.title('Profile')
I guess the error is self-explanatory. pyplot does not have a plot_surface command. There is also no indication that it should. Looking at all examples you find, plot_surface is an attribute of an axes.
ax = plt.subplot(224, projection='3d')
ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
I have this plot.
fig,ax = plt.subplots(figsize=(7.5,7.5))
ax.plot(time, y)
ax.plot(time, y1, color='red')
ax.plot(time, y2, color='black')
I want to fill the area between the black and red curves. So I am doing:
y1=np.array(y1)
y2=np.array(y2)
ax.fill_between(time, y1, y2,where=y1>=y2,color='grey', alpha='0.5')
But it returns the following:
ValueError: Argument dimensions are incompatible
In your case, you do not need to put a where condition for what you want to do. fill_between function only requires to put the maximum array and minimum array for your proposal of equal length of OX array (time in your case).
The following is an example:
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=(7.5,7.5))
time = np.linspace(0,1,100)
y = np.sin(time*10)
y1 = y - 0.5
y2 = y + 0.5
ax.plot(time, y)
ax.plot(time, y1, color='red')
ax.plot(time, y2, color='black')
ax.fill_between(time, y1, y2, color='grey', alpha='0.5')
plt.tight_layout()
plt.show()
That gives the following output:
To see how where works, change the line to this one in my example:
ax.fill_between(time, y1, y2, where=(time<0.5), color='grey', alpha='0.5')
Or this as another conditional example:
ax.fill_between(time, y1, y2, where=(y1<0.0), color='grey', alpha='0.5')
As you can see, what it makes is to create a boolean array and draws only on that points of OX axis where the condition is true.
You can make your boolean array by hand also (length of OX axis, of course).
It seems that the arguments color and alpha need to be passed as color =...,alpha=....
Correct:
ax.fill_between(x, y_min, y_max,color = color, alpha=0.1)
Wrong:
ax.fill_between(x, y_min, y_max,color, alpha=0.1)