I am trying to make an error plot but I get the error:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3])
y = np.array([17706973.57161736, 4605821.60887734, 2179197.59021156])
nor = np.array([1.21377113, 0.31571817, 0.14937884])
plt.errorbar(x, y, yerr = nor)
ErrorbarContainer object of 3 artists
and the plot does not contain error bars. Any idea?
What are you getting is not an error, it is the output of plt.errorbar. The reason you do not see the bars is because the scale of the error is way smaller than the scale of the data you are plotting. In fact, if you make the errors larger you will see them:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3])
y = np.array([17706973.57161736, 4605821.60887734, 2179197.59021156])
# Larger error.
nor = np.array([1.21377113 * 5000000, 0.31571817 * 5000000, 0.14937884 * 5000000])
plt.errorbar(x, y, yerr = nor)
Related
I want to plot with error bars in both directions. My error values are standard error. So I want the error bars to be according to the value they belong to. Here's my code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
column_names = ["gplx", "gplxerror", "hplx", "hplxerror"]
data=pd.read_csv("hw4.csv", names=column_names)
x=data.gplx.to_list()
xerr=data.gplxerror.to_list()
y=data.hplx.to_list()
yerr=data.hplxerror.to_list()
xx = [1/(i/1000) for i in x]
yy = [1/(j/1000) for j in y]
plt.errorbar(xx, yy, xerr, yerr, fmt='o',
ecolor='pink', color='blue')
plt.xlabel('Gaia Distance(in pc)')
plt.ylabel('Hipparcos Distance (in pc)')
plt.savefig('filename.png', dpi=600)
And this is the plot that I get:
But the error bars are too big. How can I make them smaller?
I used (error/100 * value) to get error as percentage of each value. It worked well. Check the following code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
column_names = ["gplx", "gplxerror", "hplx","hplxerror"]
data=pd.read_csv("hw42.csv", names=column_names)
x=data.gplx.to_list()
xerr=data.gplxerror.to_list()
y=data.hplx.to_list()
yerr=data.hplxerror.to_list()
xx = [1/(i/1000) for i in x]
yy = [1/(j/1000) for j in y]
xxerr = [(i/100) for i in xerr]
yyerr = [(j/100) for j in yerr]
xe= [a * b for a, b in zip(xx, xxerr)]
ye= [a * b for a, b in zip(yy, yyerr)]
plt.errorbar(xx, yy, xe, ye,fmt='.', alpha=1, ecolor='black',elinewidth=0.5, markersize=4)
plt.xlabel('Gaia Distance(in pc)')
plt.ylabel('Hipparcos Distance (in pc)')
plt.savefig('filename.png', dpi=600)
I have a 256x256 matrix of values and I would like to plot a histogram of these values
If I am not mistaken, the histogram must be calculated in a vector of values, correct? so here is what I have tried:
from skimage.measure import compare_ssim
import numpy as np
import matplotlib.pyplot as plt
d = np.load("BB_Digital.npy")
n, bins, patches = plt.hist(x=d.ravel(), color='#0504aa', bins='auto', alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Blue channel Co-occurency matrix')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
But then, I have a very strange result:
When I don't use the ravel function (use the 2D matrix) the following result is shown:
However, both histograms seem to be wrong, as I verified later:
>>> np.count_nonzero(d==0)
51227
>>> np.count_nonzero(d==1)
2529
>>> np.count_nonzero(d==2)
1275
>>> np.count_nonzero(d==3)
885
>>> np.count_nonzero(d==4)
619
>>> np.count_nonzero(d==5)
490
>>> np.count_nonzero(d==6)
403
>>> np.max(d)
12518
>>> np.min(d)
0
How can I build a correct histogram?
P.s: Here is the file if you could help me.
The data seems to be discrete. Setting explicit bin boundaries at the halves could show the frequency of each value. As there are very high but infrequent values, the following example cuts off at 50:
import numpy as np
from matplotlib import pyplot as plt
d = np.load("BB_Digital.npy")
plt.hist(d.ravel(), bins=np.arange(-0.5, 51), color='#0504aa', alpha=0.7, rwidth=0.85)
plt.yscale('log')
plt.margins(x=0.02)
plt.show()
Another visualization could show a pcolormesh where the colors use a logarithmic scale. As the values start at 0, adding 1 avoids minus infinity:
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
d = np.load("BB_Digital.npy")
plt.pcolormesh(d + 1, norm=LogNorm(), cmap='inferno')
plt.colorbar()
plt.show()
Yet another visualization concentrates on the diagonal values:
plt.plot(np.diagonal(d), color='navy')
ind_max = np.argmax(np.diagonal(d))
plt.vlines(ind_max, 0, d[ind_max, ind_max], colors='crimson', ls=':')
plt.yscale('log')
I am trying to do a 3D quiver plot and combining it with odeint to solve a linearized equation. Basically, I want something similar to this but in 3D. The particular issue I am having is that near the end of the code, when I am doing the ax.quiver() plot, I keep getting the error that "val must be a float or nonzero sequence of floats", and I am unsure how to resolve it.
from scipy.integrate import odeint
from numpy import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax =fig.add_subplot(1, 1, 1, projection='3d')
ax.set_xlabel('x')
ax.set_ylabel('u')
ax.set_zlabel('u1')
def testplot(X, t=0,c=0.2):
x = X[0]
u = X[1]
u1=X[2]
dxdt =x**2*(-1+x+u)*(1-x+(-1+c)*u**2)
du1dt =c**2*u*(2+x*(-4+2.25*x)+(-4 + 4*x)*u**2 + 2*u**4 + x**2*u*u1)
dudt=u1*dxdt
return [dxdt, dudt,du1dt]
X0 = [0.01,0.995,-0.01]#initial values
t = linspace(0, 50, 250)
c=[0.2,0.5,1,2]#changing parameter
for m in c:
sol = odeint(testplot,X0,t,mxstep=5000000,args=(m,))#solve ode
ax.plot(sol[:,0],sol[:,1],sol[:,2],lw=1.5,label=r'$c=%.1f$'%m)
x = linspace(-3,3,15)
y = linspace(-4,4,15)
z= linspace(-2,2,15)
x,y,z = meshgrid(x,y,z) #create grid
X,Y,Z = testplot([x,y,z])
M = sqrt(X**2+Y**2+Z**2)#magnitude
M[M==0]=1.
X,Y,Z = X/M, Y/M, Z/M
ax.quiver(x,y,z,X,Y,Z,M,cmap=plt.cm.jet)
ax.minorticks_on()
ax.legend(handletextpad=0,loc='upper left')
setp(ax.get_legend().get_texts(),fontsize=12)
fig.savefig("testplot.svg",bbox_inches="tight",\
pad_inches=.15)
Looks like you have an extra argument in ax.quiver(). From what I can tell, it looks like "M" is the extra argument. Taking that out, your quiver call looks like:
ax.quiver(x,y,z,X,Y,Z,cmap=plt.cm.jet)
The resulting image looks like:
Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:
import matplotlib.pyplot as pyplot
import math
e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)
Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...
Any advice is greatly appreciated!
When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.
From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)
import numpy as np
import matplotlib.pyplot as plt
# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e
plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()
Edit
Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x = np.linspace(1, 4, 1000)
y = x**3
fig, ax = plt.subplots()
ax.loglog(x,y, basex=np.e, basey=np.e)
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
It can also works for semilogx and semilogy to show them in e and also change their name.
import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
Take a look at the image.
I'm very new to python just started using it from a day or two..
I'm using Anaconda python notebook.
so I'm trying to plot, but in the output there is only grid and nothing no lines or anything,
my program is as follows
from __future__ import print_function
from decimal import *
import numpy as np
from sympy import *
import pylab
k = Symbol('k')
A = Symbol('A')
E = Symbol('E')
d = Symbol('d')
C = Symbol('C')
Y = Symbol('Y')
Y = []
for A in np.arange(-1.11, 1.11, 0.002):
s = sin(A)
c = cos(A)
C = (s/A) + c
Y.append(C)
pylab.plot(C, A)
grid()
xlabel('$x$')
ylabel('$y$')
title('graph')
The code doesn't show any errors, but will you please help me as to what am I doing wrong here ...
You are mixing different plotting functions from pylab, sympy and you are not giving an X axis:
import numpy as np
from matplotlib import pyplot
Y=[]
X = np.arange(-1.11, 1.11, 0.002)
for A in X:
s = np.sin(A)
c = np.cos(A)
C = (s/A)+c
Y.append(C)
line, = pyplot.plot(X,Y, "-b")
pyplot.grid(True)
pyplot.show()
Gives me:
What about showing the graph with
pylab.show()
If I do this, I have a figure with both grid and graph:
import pylab
pylab.plot([1, 3, 4], [1, 2, 3])
pylab.grid()
pylab.show()
But if I do this, I have first a figure with only the graph, and then with only the grid:
import pylab
pylab.plot([1, 3, 4], [1, 2, 3])
pylab.show() # here I get only the graph
pylab.grid()
pylab.show() # here I get only the grid
Note: calling grid(), title(), xlabel and ylabel as you do shall not work; each time it shall be prepended by pylab.. Is that really your code?