Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

python - 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: enter image description here

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?
question from:https://stackoverflow.com/questions/66065830/how-to-get-the-limits-of-plotted-data-from-a-figure-or-axes-object-in-matplotlib

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...