So I made a program that does what I need, mainly plots histogram from my data, but I have a few issues with it:
Here's the program:
# -*- coding: cp1250 -*-
from __future__ import division
from numpy import *
from matplotlib import rc
from matplotlib.pyplot import *
import numpy as np
import matplotlib.pyplot as plt
data = loadtxt("mioni.txt", int)
nuz = len(data)
nsmp = 20
duz = int(nuz/nsmp)
L = []
for i1 in range(0,nsmp):
suma = 0
for i2 in range(0,duz):
suma += data[i1*duz+i2]
L.append(suma)
print L
plt.hist(L, 20, normed=1, facecolor='blue', alpha=0.75)
plt.xlabel('t(\mu s)')
plt.ylabel('Broj događaja')
plt.axis([0,10,0,300])
plt.grid(True)
plt.show()
EDIT: so I managed to deal with the ugly sums, but now my histograms don't work :(
Data is here: http://dropcanvas.com/kqjem
What's wrong? I get tons of errors and python crashes :\
The problem comes from having a discrete data set, it looks like you set the bins parameter to something that doesn't fit. Use the pylab.hist parameter histtype="stepfilled" to get them to touch without the lines. Here are a few examples:
import numpy as np
import pylab as plt
# Sample data
X1 = np.random.exponential(1.0,size=5000)
X2 = [int(z) for z in X1]
plt.subplot(221)
plt.hist(X1,bins=50)
plt.title('Continuous Data')
plt.subplot(222)
plt.hist(X2,bins=50)
plt.title('Discrete Data')
plt.subplot(223)
plt.hist(X2,histtype='stepfilled')
plt.title('Discrete Data Filled')
plt.show()
use numpy.histogram: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
or matplotlib.pyplot.hist: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
for example:
plt.hist(data, bins=20)
Related
I'm trying to print a logistic differential equation and I'm pretty sure the equation is written correctly but my graph doesn't display anything.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
for num in range(len(xList)-1):
plt.plot(xList[num], eq(con,x))
x=eq(con,x)
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show()
You get nothing in your plot because you are plotting points.
In plt you need to have x array and y array (that have the same length) in order to make a plot.
If you want to do exactly what you are doing I suggest to do like this:
import matplotlyb.pyplot as plt # just plt is sufficent
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
y = np.zeros(len(xList)) # initialize an array with the same lenght as xList
for num in range(len(xList)-1):
y[num] = eq(con,x)
x=eq(con,x)
plt.figure() # A good habit is always to use figures in plt
plt.plot(xList, y) # 2 arrays of the same lenght
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show() # now you should get somthing here
I hope that this helps you ^^
I plotted some values from my experiment output by the spider(anaconda). I want to change x axis scientific notation from 1e-05 to 1e-06. I googled and could not find a relevant solution to this problem. please help
enter code here
#Import Libraries
import numpy as np
import csv
import matplotlib.pyplot as plt
import pylab
import style
#Handling value error
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
#import csv file
with open( 'try1.csv', 'r') as i:
file01= list(csv.reader(i,delimiter=','))[2:]
file02=[[float(k) if (isfloat(k)) else 0 for k in j] for j in file01] # Picking the values only
#creating a mumpy array
Data= np.array(file02, dtype=float)
xdata= Data[:,0][::280]
ydata= Data[:,1][::280]
#Plot
plt.figure(1,dpi=800)
plt.title('Force Spectroscopy')
plt.ylabel('Vertical Deflection')
plt.xlabel('Measured Height')
plt.style.use(['seaborn_grid'])
plt.plot(xdata,ydata, color='green',label=('Experimental data'))
#Theoritical Plot
new= -(0.107e-5)*xdata
plt.plot(xdata,new, color= 'purple',label='Theoritical')
#Legend Modification
plt.legend('upper right',fontsize=20)
plt.legend()
Output image of my plot. see the axis notation 1e-5
you can use ticklabel_format() to set the tick label format. You can add the following line -> plt.ticklabel_format(style='sci', axis='x', scilimits=(-6,-6)) to your code to have the x-axis in e-06. Note that the -6 to -6 is telling matplotlib to set the format from e-06 to e-06. More info here
Your modified code sample here to demonstrate the same...
Code
import numpy as np
import matplotlib.pyplot as plt
import pylab
import style
xdata = np.array([1.21, 1.32, 2.54]) * (1e-5)
ydata = [1, 4, 15]
#Plot
plt.figure(1,dpi=800)
plt.title('Force Spectroscopy')
plt.ylabel('Vertical Deflection')
plt.xlabel('Measured Height')
plt.plot(xdata,ydata, color='green',label=('Experimental data'))
#Theoritical Plot
new= -(0.107e-5)*np.array(xdata)
plt.plot(xdata,new, color= 'purple',label='Theoritical')
plt.ticklabel_format(style='sci', axis='x', scilimits=(-6,-6))
#Legend Modification
plt.legend('upper right',fontsize=20)
plt.legend()
Output
as the title suggests, this is a straightforward question: ticklabel_format simply has no effect whatsoever on my figure.
here's the script:
import sys
import math
import yaml
import numpy as np
import matplotlib.pyplot as plt
dwarf = sys.argv[1]
pts = np.empty([100,100])
fig = plt.figure()
fig.suptitle('J value - %s'%dwarf,fontsize=18)
m = plt.imshow(pts,cmap='rainbow',extent=[-2,2,5,9])
plt.xlabel(r'$r_s [kpc]$',fontsize=18)
plt.ylabel(r'$\rho_s [M_{sun} kpc^{-3}]$',fontsize=18)
plt.ticklabel_format(style='sci',axis='x',scilimits=(-2,2))
plt.ticklabel_format(style='sci',axis='y',scilimits=(5,9))
plt.grid()
cx = plt.colorbar(m,pad=0)
cx.set_label(r'$log_{10}(J(\rho_s,r_s))$',fontsize=18)
plt.savefig('output/gridJ_%s.png'%dwarf,dpi=100,format='png')
plt.show()
on the produced plot, the ticks on the axes are simply the values dictated by extent kwarg in plt.imshow and not the nice scientific notation 10**n I would like it to have.
Any idea why it's misbehaving? Thank you
Just use matplotlib.pyplot.ylim or matplotlib.pyplot.xlim to set the limits.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab`
mu = np.loadtxt('my_data/corr.txt')
d = mu[:,2]
y=[]
tot=0
min=999
for i in d:
y.append(float(i))
tot=tot+float(i)
if (min>float(i)):
min=float(i)
av=tot/len(y)
z=[]
m=[]
for i in y:
z.append(i-av)
m.append(i-min)
plt.acorr(z,usevlines=True,maxlags=None,normed=True)
plt.show()
WIth this code I have the output showing a bar chart.
Now,
1) How do I change this plot style to give just the trend line? I cant modify the line properties by any means.
2) How do I write this output data to a dat or txt file?
this should be a working minimal example:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import normal
data = normal(0, 1, 1000)
# return values are lags, correlation vector and the drawn line
lags, corr, line, rest = plt.acorr(data, marker=None, linestyle='-', color='red', usevlines=False)
plt.show()
np.savetxt("correlations.txt", np.transpose((lags, corr)), header='Lags\tCorrelation')
But i would recommand not to connect the points.
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.