42

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.

7
  • 1
    mpl mailing lists -> sourceforge.net/mail/?group_id=80706 Commented Jun 3, 2013 at 19:53
  • 2
    possible duplicate of Matplotlib logarithmic scale with zero value Commented Jun 3, 2013 at 19:55
  • Above question has two possible solutions for this. Commented Jun 3, 2013 at 19:55
  • @honk - Actually, that question doesn't answer the OP's question. Commented Jun 3, 2013 at 19:59
  • @JoeKington: I wasn't aware of symlog which is also a nice answer to the question I linked to. When using it one still needs to keep in mind that the displayed plot isn't strictly a logplot anymore though. Commented Jun 3, 2013 at 20:13

1 Answer 1

64

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer. Thanks for that. Could you elaborate what symlog is exactly doing?
Sure! See the updates. There are also a few examples in the matplotlib gallery (e.g. matplotlib.org/examples/pylab_examples/symlog_demo.html ), but they're not as clear as the SO answer I linked to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.