title: Get number of data points in visible range
body: <p>In a particular Matplotlib graph I want the linestyle to change dynamically based on the number of points on screen (basically, switch from <code>-</code> to <code>-o</code> when there are sufficiently low number on data points). </p>
  
  <p>For that, first I need to get the number of data points on screen. I wrote a code sample below that does that using the function <code>get_view_interval</code>.</p>
  
  <pre><code>import matplotlib.pyplot as plt
  
  def get_Npoints_on_screen(ax=None, line_index=0):
      ''' 
      Input
      -----
      ax: matplotlib axe
      l: line number
      '''
  
      if ax is None:
          ax=plt.gca()
      line = ax.get_lines()[line_index]
  
  
      xmin, xmax = ax.xaxis.get_view_interval()
      ymin, ymax = ax.yaxis.get_view_interval()
  
      xdata = line.get_xdata()
      ydata = line.get_ydata()
  
      return sum((xdata&gt;=xmin) &amp; (xdata&lt;=xmax) &amp; (ydata&gt;=ymin) &amp; (ydata&lt;=ymax))
  
  
  # Just a figure to play with
  if __name__ == '__main__':
      from numpy import linspace, pi, cos
      x = linspace(0,4*pi,100)
  
      plt.plot(x,cos(x),'ok')
  
      print(get_Npoints_on_screen(),'points on screen')
  
      plt.waitforbuttonpress()
      plt.xlim((0,pi))
  
      print(get_Npoints_on_screen(),'points on screen')
  </code></pre>
  
  <p>It works, but I don't find it very elegant. Is there a more straightforward way of getting the number of visible points on screen in Matplotlib?</p>