Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logarithmic y-axis bins in python

I'm trying to create a histogram of a data column and plot it logarithmically (y-axis) and I'm not sure why the following code does not work:

import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('foo.bar') fig = plt.figure() ax = fig.add_subplot(111) plt.hist(data, bins=(23.0, 23.5,24.0,24.5,25.0,25.5,26.0,26.5,27.0,27.5,28.0)) ax.set_xlim(23.5, 28) ax.set_ylim(0, 30) ax.grid(True) plt.yscale('log') plt.show() 

I've also tried instead of plt.yscale('log') adding Log=true in the plt.hist line and also I tried ax.set_yscale('log'), but nothing seems to work. I either get an empty plot, either the y-axis is indeed logarithmic (with the code as shown above), but there is no data plotted (no bins).

like image 707
mannaroth Avatar asked Jul 30 '13 16:07

mannaroth


People also ask

How do you make the Y axis log in Python?

pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively. The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib.

How do I change the y axis values in Python?

To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.


2 Answers

try

plt.yscale('log', nonposy='clip') 

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.yscale

The issue is with the bottom of bars being at y=0 and the default is to mask out in-valid points (log(0) -> undefined) when doing the log transformation (there was discussion of changing this, but I don't remember which way it went) so when it tries to draw the rectangles for you bar plot, the bottom edge is masked out -> no rectangles.

like image 198
tacaswell Avatar answered Oct 09 '22 09:10

tacaswell


np.logspace returns bins in [1-10], logarithmically spaced - in my case xx is a npvector >0 so the following code does the trick

logbins=np.max(xx)*(np.logspace(0, 1, num=1000) - 1)/9 hh,ee=np.histogram(xx, density=True, bins=logbins) 
like image 30
Luca Rigazio Avatar answered Oct 09 '22 10:10

Luca Rigazio