简体   繁体   中英

Access data in matplotlib histogram axes

Where is the data plotted stored in a matplotlib ax object drawing a histogram?

My scenario: I've written a function which draws a custom histogram using matplotlib. I am writing a unit test and would like to test whether the plotted data

Ideal behaviour:

import matplotlib.pyplot as plt

f, ax = plt.subplots()
ax.hist(some_data)
data_i_want = ax.plotted_data

I'm not sure what exactly you want to achieve, but the plt.hist(...) function returns the data for the histogram:

histinfo = plt.hist(data)
histinfo[0] #This is the information about the # of instances
histinfo[1] #This is the information about the position of the bins

If you want to get the information from the plot itself at all cost (assuming you have a barplot):

container = ax.containers[0] #https://matplotlib.org/3.1.1/api/container_api.html
for rect in container: #https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle
    print(rect.xy)

You can get the containers, and those containers will contain the information about the plotted bars (rectangles) at the commented URL, you can find every information about that.

Ps.: You probably have to adapt the code for the specific instance, but this is a way to get some information from the plot. (It is possible that there is a better way to do it, this is the best i know)

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