Difference between fill_between and fill_betweenx matplotlib - python

I cannot understand how to use fill_betweenx() in matplotlib. How it is different from fill_between()? After reading the documentation of fill_betweenx() I tried to implement it:
x=np.linspace(0,2*3.14,50)
y=np.sin(x)
plt.figure(figsize=(10,5))
plt.fill_betweenx(y,2,3,color='b')
plt.plot(x,y)
As per my understanding, it should have filled the sine curve between x=2 and x=3 with a blue color, but I got:
Can anyone explain to me why it wasn't filled?

It seems you want to fill the sine curve, e.g. between y=0 and the sine. You may limit this fill to a range of x coordinates using where.
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,2*3.14,50)
y=np.sin(x)
plt.fill_between(x,y,0,where=(x>2) & (x<=3),color='b')
plt.plot(x,y)
In contrast you would use fill_betweenx if you wanted to fill between a curve in x direction. E.g.
plt.fill_betweenx(x,y,where=(x>2) & (x<=3), color='b')
plt.plot(y,x)

Related

Difficulties using matplotlib plot method

Very recently I have been tasked with ploting a derivative using Python and matplotlib. This is my code:
x=np.linspace(-100,100,num=50)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
The resulting plot is this:
Plot generated in Python
At first sight, the graph looks okay, but is not correct, given that the graph is suposed to look like this:
Correct plot
How can I fix this? I have tried changing the linespace a bunch of times, and the results are the same.
I've tried to plot a derivate in matplotlib and the graph is incorrect.
The problem is not with matplotlib, but instead the range of x values you chose. If you look at your own picture, the xvalues are ranging from around -2 to 2, so if I do the same and play with the plotting bounds I get:
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-2,2,101)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
plt.axvline(0, color = 'k')
plt.axhline(0, color = 'k')
plt.xlim([-0.8, 1.4])
plt.ylim([-3.5, 3])
which gives

python matplotlib polar plot

I am using the following code to create a polar plot of the sinus.
import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0, 2*np.pi, .01)[1:]
plt.polar(theta, sin(theta))
plt.show()
which produces:
but I want to plot it symmetrically, like this:
How can I get the result I want?
The matplotlib polar allows for negative radius. So, if you want the symmetric plot you need to plot the absolute value of sin:
polar(theta, abs(sin(theta)))
Anon, you need to plot the opposite of sin(theta):
plt.polar(theta, sin(theta))
plt.polar(theta, -sin(theta))

Removing wireframe without gaps in matplotlib plot_trisurf

I want to create a smooth cylinder using matplotlib/pyplot. I've adapted a tutorial online and produced the following minimal example:
from numpy import meshgrid,linspace,pi,sin,cos,shape
from matplotlib import pyplot
import matplotlib.tri as mtri
from mpl_toolkits.mplot3d import Axes3D
u,v = meshgrid(linspace(0,10,10),linspace(0,2*pi,20))
u = u.flatten()
v = v.flatten()
x = u
z = sin(v)
y = cos(v)
tri = mtri.Triangulation(u, v)
fig = pyplot.figure()
ax = fig.add_axes([0,0,1,1],projection='3d')
ax.plot_trisurf(x,y,z,triangles=tri.triangles,linewidth=0)
pyplot.show()
which produces a cylinder. I set linewidth=0 to remove the wireframe, however, there is now the "ghost" of the wireframe because the triangulation has (presumably) been spaced assuming the wireframe is there to fill in the gaps. This looks to be specific to plot_trisurf, because there are other 3d plotting examples (e.g., using plot_surface) which set linewidth=0 without these gaps showing up.
Doing an mtri.Triangulation?, it seems like it might not be possible to "perfectly" fill in the gaps, since it states
>Notes
> -----
> For a Triangulation to be valid it must not have duplicate points,
> triangles formed from colinear points, or overlapping triangles.
One partial solution is to just color the wireframe the same shade of blue, but after I've fixed this problem I also want to add a light source/shading on the surface, which would put me back at square one.
Is there a way to make this work? Or can someone suggest a different approach? Thanks for any help.
ax.plot_trisurf(x,y,z,triangles=tri.triangles,linewidth=0, antialiased=False)

2D Map in matplotlib with discrete values

I'm currently trying to plot with matplotlib a 2d map recorded with an instrument. The instrument is moving 2 motors (it makes a raster) and records the associated intensity value.
I'm currently able to plot the data and to associate the values I want to the axes, but I would like to digitize (make discrete) these values in order to obtain at each pixel of the image the corresponding values for the motors.
I'm currently using the following code (in the example I'll use x and y to define the motor positions):
import pylab as pl
pl.imshow(intensity, extent=(x_min, x_max, y_min, y_max),
interpolation='none')
The code works quite well but if I select one of the pixel on my plot with the cursor, it returns continuous values with many digits (like in figure).
Would it be possible to obtain directly the values of the motors (which I have stored for each point/pixel) by positioning the cursor on them?
Thanks for the help,
Fabio
You can do it by modifying the coordinate formatter like in this example on the matplotlib documentation. A simple adaptation to your request is:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
X = 10*np.random.rand(5, 3)
fig, ax = plt.subplots()
ax.imshow(X, cmap=cm.jet, interpolation='nearest')
def format_coord(x, y):
return 'x=%i, y=%i' % (x+1, y+1)
ax.format_coord = format_coord
plt.show()
, which will result in this:
Also you might want to check out mpldatacursor for something more pretty. For this option take a look at this question here in SO.

Matplotlib : quiver and imshow superimposed, how can I set two colorbars?

I have a figure that consists of an image displayed by imshow(), a contour and a vector field set by quiver(). I have colored the vector field based on another scalar quantity. On the right of my figure, I have made a colorbar(). This colorbar() represents the values displayed by imshow() (which can be positive and negative in my case). I'd like to know how I could setup another colorbar which would be based on the values of the scalar quantity upon which the color of the vectors is based. Does anyone know how to do that?
Here is an example of the image I've been able to make. Notice that the colors of the vectors go from blue to red. According to the current colorbar, blue means negative. However I know that the quantity represented by the color of the vector is always positive.
Simply call colorbar twice, right after each plotting call. Pylab will create a new colorbar matching to the latest plot. Note that, as in your example, the quiver values range from 0,1 while the imshow takes negative values. For clarity (not shown in this example), I would use different colormaps to distinguish the two types of plots.
import numpy as np
import pylab as plt
# Create some sample data
dx = np.linspace(0,1,20)
X,Y = np.meshgrid(dx,dx)
Z = X**2 - Y
Z2 = X
plt.imshow(Z)
plt.colorbar()
plt.quiver(X,Y,Z2,width=.01,linewidth=1)
plt.colorbar()
plt.show()
Running quiver doesn't necessarily return the type of mappable object that colorbar() requires. I think it might be because I explicitly "have colored the vector field based on another scalar quantity" like Heimdall says they did. Therefore, Hooked's answer didn't work for me.
I had to create my own mappable for the color bar to read. I did this by using Normalize from matplotlib.colors on the data that I wanted to use to color my quiver vectors (which I'll call C, which is an array of the same shape as X, Y, U, and V.)
My quiver call looks like this:
import matplotlib.pyplot as pl
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.colorbar as mcolorbar
pl.figure()
nz = mcolors.Normalize()
nz.autoscale(C)
pl.quiver(X, Y, U, V, color=cm.jet(nz(C)))
cax,_ = mcolorbar.make_axes(pl.gca())
cb = mcolorbar.ColorbarBase(cax, cmap=cm.jet, norm=nz)
cb.set_label('color data meaning')
Giving any other arguments to the colorbar function gave me a variety of errors.

Categories

Resources