How to auto-update ylim for nans in x due to xscale(log)

53 Views Asked by At

I am plotting my data (x,y) and want to show the x-axis in logscale. Because there are some negative values in x, the log10 can not be computed for all. This results in nans which are simply omitted when plotting (and this is what I want) but the y-axis limits are not updated for these missing values.

Example:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 11, 1) 
plt.plot(x,x, marker='d')

enter image description here

and when I add the log scale on the x-axis, the negative values are omitted but the y-axis is not updated

x = np.arange(-10, 11, 1) 
plt.plot(x,x, marker='d')
plt.xscale('log')

enter image description here

Of course I could manually set ylim but that is not ideal if I don't know the exact values by head. I am puzzled that matplotlib doesn't update this automatically... ax.relim() and ax.autoscale_view() did not help. Any ideas/opinions?

2

There are 2 best solutions below

0
swagner On BEST ANSWER

I worked out how to fix the issue in a generalized manner: If the xscale is set to 'log' and there are negative values in x, take the position of minimum of x < 0 and set y value at that position as new limit (ideally with the same margin as in the rest of the figure):

margin = 0.1
if len(x[x<0]) !=0 and ax.get_xscale=='log':
    ii_x_g0 = np.min(np.where(x>0))
    ax.set_ylim(bottom = y[ii_x_g0] - y[ii_x_g0] * margin)

As I said, I am surprised matplotlib doesn't do this automatically so I submitted this GitHub Issue for matplotlib. Lets see what they think and say about it...

1
Denilson Sá Maia On

After a quick look at the documentation, I would suggest you to try set_ylim(bottom=0.0) or set_ybound(lower=0.0) or ylim(bottom=0.0).

In fact, I made it work with your example by just adding one single line:

plt.ylim(bottom=0.0)