从生成器函数传递多个matplotlib轴对象并显示它们

2024-09-28 22:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在generator函数中创建几个带有pandas的直方图,将它们作为matplotlib轴对象的列表传递给主函数,然后逐个显示它们。

我的代码在下面。第一个图显示OK,但是当我试图显示第二个图时,我得到了:“ValueError:Axes instance argument was not found in a figure.”

这个错误消息是什么意思?我怎么修?

import argparse
import matplotlib.pyplot as plt
import pandas as pd

def make_hist(n,input_data,Xcolname,bins):
    curr_num=0
    while curr_num<n:
        afig = input_data[curr_num][Xcolname].hist(bins=bins)
        yield afig
        curr_num=curr_num+1

 def main():    
    filepath = "C:/Users/Drosophila/Desktop/test.txt"
    filepath2="C:/Users/Drosophila/Desktop/test.txt"
    input_data = load_data_from_file([filepath,filepath2],concatenate=False)

    Xcolname = 's5/s6'

    pd.options.display.mpl_style = 'default'    

    bins=10

    n=2

    figs=list(make_hist(n,input_data,Xcolname,bins))

    plt.sca(figs[0])
    plt.show()

    plt.sca(figs[1])
    plt.show()

if __name__ == '__main__':
    main()

Tags: 函数importpandasinputdatamatplotlibmainas
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:47

最小化直方图生成器的问题:

import matplotlib.pyplot as plt
import pandas as pd
from numpy.random import random

def make_hist(input_data,bins):
    for row in input_data:
        print(row) # micro-testing: do the hists look about right?
        bin_edges, bin_heights, patches = plt.hist(row, bins=bins)
        yield patches


input_data = random((3, 6))

pd.options.display.mpl_style = 'default'

fig = plt.figure()
for patches in make_hist(input_data, 10):
    plt.show() 
    fig.clf() 

您的主要问题是运行hist时不会返回一个轴,即使hist使用了一个轴。在

另外,我认为您使用的是一个不需要生成器的地方(传入n似乎是向后的),尽管很难脱离上下文来区分。为什么不在有一个plotsworth时循环数据并绘制?或者每个n x mplotsworth,如果您想要n行m列的图形。在

相关问题 更多 >