Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logscale plots with zero values in matplotlib

I am currently using logscale in order to have greater possibilities of plotting my data. Nevertheless, my data consists also of zero values. I know that these zero values will not work on logscale as log(0) is not defined.

So e.g.,

fig = plt.figure() ax = fig.add_subplot(111) ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-') ax.set_yscale('log') ax.set_xscale('log') 

completely omits the zero value. Is this behavior acceptable? At least there should be some kind of warning. I only recognized it by accident. Is there maybe also a way of plotting zero value data in logscale?

Thanks!

P.S.: I hope this fits to stackoverflow. I did not find a mailing list of matplotlib.

like image 780
fsociety Avatar asked Jun 03 '13 19:06

fsociety


People also ask

How do you plot zeros on a log scale?

The logarithm of zero is not defined -- its mathematically impossible to plot zero on a log scale. Instead of entering zero, you can enter a low value (say -10 on the log scale), and then use custom ticks to label the graph correctly (so it is labeled "0" rather than "-10".

Why is PLT plot blank?

The reason your plot is blank is that matplotlib didn't auto-adjust the axis according to the range of your patches. Usually, it will do the auto-adjust jobs with some main plot functions, such as plt. plot(), plt.

Is PLT show () necessary?

Plotting from an IPython shell Using plt. show() in Matplotlib mode is not required.


1 Answers

It's easiest to use a "symlog" plot for this purpose. The interval near 0 will be on a linear scale, so 0 can be displayed.

import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-') ax.set_yscale('symlog') ax.set_xscale('symlog') plt.show() 

enter image description here

Symlog sets a small interval near zero (both above and below) to use a linear scale. This allows things to cross 0 without causing log(x) to explode (or go to -inf, rather).

There's a nice visual comparison as an SO answer here: https://stackoverflow.com/a/3513150/325565

like image 118
Joe Kington Avatar answered Oct 06 '22 16:10

Joe Kington