如何在Python中绘制函数的输出?

时间:2013-07-14 15:04:59

标签: python matplotlib

这三个功能为我提供了从0州到下365个州(或几天)的客户数量和订单数量的增长。在function state_evolution中,我想绘制行

的输出
custA = float(custA*1.09**(1.0/365))

反对行

的输出
A = sum(80 + random.random() * 50 for i in range(ordsA))

并对custB执行相同的操作,以便我可以以图形方式比较它们的输出。

def get_state0():
    """ functions gets four columns from base data and finds their state 0"""
    statetype0 = {'custt':{'typeA':100,'typeB':200}}
    orderstype0 = {'orders':{'typeA':1095, 'typeB':4380}}
    return  {'custtypeA' : int(statetype0['custt']['typeA']),
             'custtypeB' : int(statetype0['custt']['typeB']),
             'ordstypeA': orderstype0['orders']['typeA'],'A':1095, 'B':4380,
             'ordstypeB':orderstype0['orders']['typeB'], 
             'day':0 }  


def state_evolution(state):
    """function takes state 0 and predicts state evolution """
    custA = state['custtypeA']
    custB = state['custtypeB']
    ordsA = state['ordstypeA']
    ordsB = state['ordstypeB']
    A = state['A']
    B = state['B']
    day = state['day']   
    # evolve day
    day += 1
    #evolve cust typea
    custA = float(custA*1.09**(1.0/365))
    #evolve cust typeb
    custB = float (custB*1.063**(1.0/365))
    # evolve orders cust type A 
    ordsA += int(custA * order_rateA(day))
    A = sum(80 + random.random() * 50 for i in range(ordsA))
    # evolve orders cust type B 
    ordsB += int(custB * order_rateB(day))
    B = sum(70 + random.random() * 40 for i in range(ordsB))
    return {'custtypeA':custA ,'ordstypeA':ordsA, 'A':A, 'B':B,
            'custtypeB':custB, 'ordstypeB':ordsB, 'day': day}


def show_all_states():
    """ function runs state evolution function to find other states"""
    s  = get_state0() 
    for day in range(365):
        s = state_evolution(s)

        print day, s

1 个答案:

答案 0 :(得分:0)

您应该执行以下操作:

  1. 修改您的custA函数,使其返回一个序列(list,tuple),例如365项。或者,在列表推导中使用custA或使用循环来获取365结果的序列;
  2. ordsA函数执行相同操作,以获取其他序列。
  3. 从现在开始,您可以根据自己的需要做不同的事情。

    如果你想要两个平行的图(叠加),那么:

    pyplot.plot(custA_result_list);
    pyplot.plot(ordsA_result_list);
    pyplot.show()
    

    如果要对数据进行相关,可以使用点标记(更慢但更可自定义的IMO)执行散点图(更快)或常规绘图:

    pyplot.scatter(custA_result_list, ordsA_result_list)
    # or
    pyplot.plot(custA_result_list, ordsA_result_list, 'o')
    
    ## THIS WILL ONLY WORK IF BOTH SEQUENCES HAVE SAME LENGTH! (e.g. 365 elements each)
    

    最后,如果数据被不规则地采样,您还可以提供水平轴值的序列。例如,这将允许仅绘制工作日的结果,而不会在周末“崩溃”(否则星期五和星期一之间的差距看起来就像一天):

    weekdays = [1,2,3,4,5, 8,9,10,11,12, 15,16,17,18,19,  22, ...] # len(weekdays) ~ 260
    
    pyplot.plot(weekdays, custA_result_list);
    pyplot.plot(weekdays, ordsA_result_list);
    pyplot.show()
    

    希望这有帮助!

    编辑:关于excel,如果我理解正确你ALREADY有一个csv文件。然后,您可以使用csv python模块,或者像这样自己阅读:

    with open('file.csv') as csv_in:
        content = [line.strip().split(',') for line in csv_in]
    

    现在,如果您有实际的.xls.xlsx文件,请使用可以下载herexlrd模块或在命令中运行pip install xlrd提示。