简体   繁体   中英

How to get the limits of plotted data from a Figure or Axes object in Matplotlib?

I'm trying to determine what the limits of data points are on a matplotlib Axes or Figure, but I can't find any way. I'm gonna give an example, but the original image is much more complex: 在此处输入图像描述

By using Axes.get_xbound() or Axes.get_xlim() I get (-265.6, 6000.0) but I would want to get (0,5570).

I'm asking this because on this part of code I only have access to the Figure or Axes object. Something like this:

def plot_detail():
    fig, ax = plt.subplots(1)
    # Code
    # ...
    return fig,ax

def main():
    fig,ax = plot_detail()
    print(ax.get_xbound())
    print(ax.get_xlim())
    # Here I would need the data limits
    # Any Idea how?

First, just as a side note, from the fact that you want the data at point in the code where you only have the plot (Figure and Axes), it seems to me that there was at least one not-so-great design decision made while designing/writing your code. If I could see the whole code I could likely recommend a better approach. That said, it is understandable that sometimes we don't anticipate all the needs of our code, and then sometimes (depending on the size of the program) it may not be worth the effort for a redesign/rewrite of part of the code.

So to get the data (in order to know the x-limits of the data itself, and not just of the plot)... You can do this by getting the lines.Line2D objects from the Axes object.

Even though it appears you are plotting a bar graph, there should still be a line2D object in there. That object contains the xy data.

xdata = ax.get_lines()[0].get_xdata()
print('xdata limits:',xdata[0],xdata[-1])

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM