Difficulties using matplotlib plot method - python

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

Related

Matplotlib | Python | Plotting figure A and then plotting another figure B on top of figure A

The fragment of code below plots a figure based on two arrays of floats
plt.scatter(t, h)
plt.xlabel("time")
plt.ylabel("height")
plt.show()
Then, after defining a function y(t), I need to add the following on top of the last plot:
plt.plot(t, y(t), 'r')
plt.show()
However, the code above generates two separate plots. I've noticed that if I comment out the first plt.show(), I'll get the second figure I am looking for. But is there a way to show them both?
I was expecting one plot and then another plot on top of the second one; however the second plot is shown as a new one
plt.show() draws your figure on screen.
So, you need to remove the first plt.show() from your code.
If you remove the first plt.show() you should see the joint plot. The first plt.scatter just produces points on the joints of the line.
import numpy as np
import matplotlib.pyplot as plt
t = np.random.random(10)
h = np.random.random(10)
plt.scatter(t, h)
plt.plot(t, h, 'r')
plt.show()
The scatter plot is just the blue dots

Difference between fill_between and fill_betweenx matplotlib

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)

Why are my points not being plotted?

I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
Your xticks are completely out of the range where your data lives. Remove the line which sets the xticks and your plot is fine
import matplotlib.pyplot as plt
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-03],
[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
If you want to use your custom ticks, you need to set them in the data range, i.e. somewhere between 0 and 0.002 and not between 1 and 7.
Your data has x values well below 0.01, while your ticks start at 1, so your data will be to the left of the plot. I would suggest using a logarithmic x axis, just like the example below. This will also fix the problem with the x values being of different orders of magnitude. Note that I also put the tick strings in reverse order, assuming that you mistakenly wrote them the other way round. If not, please just go ahead and re-reverse them!
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
x = [1.95e-06, 9.75e-06, 1.95e-05, 9.75e-05, 1.95e-04, 9.75e-04, 1.95e-03]
#ploting out the points while labeling the graph
plt.semilogx(x ,[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks(x, [str('1.95E-03'), str('9.75E-04'), str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'), str('1.95E-06')], rotation=45)
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.tight_layout()
plt.savefig('points.png')
plt.show()
The first argument to plt.xticks should be x-coords (not tick indexes).

matplotlib imshow how to plot points instead of image?

Here is the code:
plots=imshow(Z,extent=extent,origin,cmap=cmap,aspect='auto',vmin=vmin,vmax=vmax)
plots.plot(Response,component,vrange)
It plots an image based on data list Z, how can I let it print data points instead of an image?
Looks like needs to change to scatter(x, y,...) to plot data points, how difficult it is to change array Z to x, y?
As #jdj081 said, you want to produce a scatter plot.
import os.path
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# get an image from the sample data directory
fname = os.path.join(matplotlib.get_data_path(), 'sample_data', 'lena.png')
im = plt.imread(fname)
# Reduce the data by a factor of 4 (so that we can see the points)
im = im[::4, ::4]
# generate coordinates for the image. Note that the image is "top down", so the y coordinate goes from high to low.
ys, xs = np.mgrid[im.shape[0]:0:-1, 0:im.shape[1]]
# Scatter plots take 1d arrays of xs and ys, and the colour takes a 2d array,
# with the second dimension being RGB
plt.scatter(xs.flatten(), ys.flatten(), s=4,
c=im.flatten().reshape(-1, 3), edgecolor='face')
plt.show()
You didn't provide much information to go on, but it sounds like you really want to create a scatter plot.
There are many options here depending on what you are plotting and what you want to see, but I have found the following helpful:
Fixing color in scatter plots in matplotlib
import pylab
pylab.figure(1)
pylab.plot([1,2,3,4],[1,7,3,5]) # draw on figure one
pylab.show() # show figure on screen

Number density contours in Python

I'm trying to reproduce this plot in python with little luck:
It's a simple number density contour currently done in SuperMongo. I'd like to drop it in favor of Python but the closest I can get is:
which is by using hexbin(). How could I go about getting the python plot to resemble the SuperMongo one? I don't have enough rep to post images, sorry for the links. Thanks for your time!
Example simple contour plot from a fellow SuperMongo => python sufferer:
import numpy as np
from matplotlib.colors import LogNorm
from matplotlib import pyplot as plt
plt.interactive(True)
fig=plt.figure(1)
plt.clf()
# generate input data; you already have that
x1 = np.random.normal(0,10,100000)
y1 = np.random.normal(0,7,100000)/10.
x2 = np.random.normal(-15,7,100000)
y2 = np.random.normal(-10,10,100000)/10.
x=np.concatenate([x1,x2])
y=np.concatenate([y1,y2])
# calculate the 2D density of the data given
counts,xbins,ybins=np.histogram2d(x,y,bins=100,normed=LogNorm())
# make the contour plot
plt.contour(counts.transpose(),extent=[xbins.min(),xbins.max(),
ybins.min(),ybins.max()],linewidths=3,colors='black',
linestyles='solid')
plt.show()
produces a nice contour plot.
The contour function offers a lot of fancy adjustments, for example let's set the levels by hand:
plt.clf()
mylevels=[1.e-4, 1.e-3, 1.e-2]
plt.contour(counts.transpose(),mylevels,extent=[xbins.min(),xbins.max(),
ybins.min(),ybins.max()],linewidths=3,colors='black',
linestyles='solid')
plt.show()
producing this plot:
And finally, in SM one can do contour plots on linear and log scales, so I spent a little time trying to figure out how to do this in matplotlib. Here is an example when the y points need to be plotted on the log scale and the x points still on the linear scale:
plt.clf()
# this is our new data which ought to be plotted on the log scale
ynew=10**y
# but the binning needs to be done in linear space
counts,xbins,ybins=np.histogram2d(x,y,bins=100,normed=LogNorm())
mylevels=[1.e-4,1.e-3,1.e-2]
# and the plotting needs to be done in the data (i.e., exponential) space
plt.contour(xbins[:-1],10**ybins[:-1],counts.transpose(),mylevels,
extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],
linewidths=3,colors='black',linestyles='solid')
plt.yscale('log')
plt.show()
This produces a plot which looks very similar to the linear one, but with a nice vertical log axis, which is what was intended:
Have you checked out matplotlib's contour plot?
Unfortunately I couldn't view yours images. Do you mean something like this? It was done by MathGL -- GPL plotting library, which have Python interface too. And you can use arbitrary data arrays as input (including numpy's one).
You can use numpy.histogram2d to get a number density distribution of your array.
Try this example:
http://micropore.wordpress.com/2011/10/01/2d-density-plot-or-2d-histogram/

Categories

Resources