【问题标题】:Python: Graph function that takes multiple optional argumentsPython:接受多个可选参数的图形函数
【发布时间】:2018-10-11 13:46:10
【问题描述】:

对于我的研究,我希望能够快速生成多个特定类型的图表,但数据略有不同(例如不同的日期或不同的传感器)。我正在尝试编写一个函数,该函数使用一些强制参数和最多 20 个可选参数来生成图形。我希望这个功能:1)当我只给它一个传感器以及给它10个传感器时,能够产生一个漂亮的图表。 2) 仅显示开始时间和结束时间之间所需的时间
我到目前为止的代码是:

import numpy as np
import pvlib as pvl
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def temp1_multiple_days(startdatetime, enddatetime, index, temp1, label1, windowtitle = 'Temperatures over time'):
    d = {'index':index, 'temp1': temp1}
    frame = pd.DataFrame(data = d)
    frame.set_index([index], inplace = True)
    frame = frame[startdatetime:enddatetime]  #slicing right dates out of large dataset
    fig, ax1 = plt.subplots()
    fig.canvas.set_window_title(windowtitle) 
    ax1.plot(frame.index, frame.temp1, label = label1)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%b-'%y"))
    ax1.xaxis.set_major_locator(mdates.DayLocator())
    ax1.set_xlim(startdatetime, enddatetime)
    ax1.set_ylabel('Temperature (°C)')
    ax1.legend(loc=1)
    fig.tight_layout
    fig.autofmt_xdate()
    plt.grid(True)
    plt.show

如果我给它 1 个传感器,这会产生所需的结果。对于更多传感器,我创建了一个新函数。所以现在我已经定义了 10 个函数,编号为 10:

def temp10_multiple_days(startdatetime, enddatetime, index, temp1, label1, temp2, label2, temp3, label3, temp4, label4, temp5, label5, temp6, label6, temp7, label7, temp8, label8, temp9, label9, temp10, label10, windowtitle = 'Temperatures over time'):
    d = {'index':index, 'temp1': temp1, 'temp2': temp2, 'temp3': temp3, 'temp4': temp4, 'temp5': temp5, 'temp6': temp6, 'temp7': temp7, 'temp8': temp8, 'temp9': temp9, 'temp10': temp10}
    frame = pd.DataFrame(data = d)
    frame.set_index([index], inplace = True)
    frame = frame[startdatetime:enddatetime]    #slicing right dates out of large dataset
    fig, ax1 = plt.subplots()
    fig.canvas.set_window_title(windowtitle) 
    ax1.plot(frame.index, frame.temp1, label = label1)
    ax1.plot(frame.index, frame.temp2, label = label2)
    ax1.plot(frame.index, frame.temp3, label = label3)
    ax1.plot(frame.index, frame.temp4, label = label4)
    ax1.plot(frame.index, frame.temp5, label = label5)
    ax1.plot(frame.index, frame.temp6, label = label6)
    ax1.plot(frame.index, frame.temp7, label = label7)
    ax1.plot(frame.index, frame.temp8, label = label8)
    ax1.plot(frame.index, frame.temp9, label = label9)
    ax1.plot(frame.index, frame.temp10, label = label10)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%b-'%y"))
    ax1.xaxis.set_major_locator(mdates.DayLocator())
    ax1.set_xlim(startdatetime, enddatetime)
    ax1.set_ylabel('Temperature (°C)')
    ax1.legend(loc=1)
    fig.tight_layout
    fig.autofmt_xdate()
    plt.grid(True)
    plt.show

现在我的问题是:如何将它变成一个可以接受 20 个或更多可选参数的函数?

【问题讨论】:

标签: python python-3.x matplotlib optional-arguments


【解决方案1】:

我找到了切片/截断问题的答案。我将整个数据框(包含所有传感器)输入到函数中。然后将整个帧在本地切片。然后将带有传感器的列作为字符串检索。

def temp_multiple_days(df, startdatetime, enddatetime, *temps, windowtitle = 'Temperatures over time'):
df = df.truncate(startdatetime, enddatetime)
fig, ax1 = plt.subplots()
fig.canvas.set_window_title(windowtitle) 
for (temp, label) in temps:
    ax1.plot(df.index, df[temp], label = label)
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%b-'%y"))
ax1.xaxis.set_major_locator(mdates.DayLocator())
ax1.set_xlim(startdatetime, enddatetime)
ax1.set_ylabel('Temperature (°C)')
ax1.legend(loc=1)
fig.tight_layout
fig.autofmt_xdate()
plt.grid(True)
plt.show     
# i then call to the function in this way:
temp_multiple_days(df, '2018-04-21 00:00:00', '2018-04-27 23:59:59', ('name of sensor 1', 'graph label 1'), ('name of sensor 2', 'graph label 2'), windowtitle= 'A nice title')

感谢您的帮助!

【讨论】:

    【解决方案2】:

    您可以使用 *args 参数(您可以将其称为 *temps 或其他任何名称 - * 是重要部分)。带有* 的参数接受任意数量的位置参数,您可以将它们作为列表循环。由于您还需要为每个参数添加一个标签,因此您可以期望每个参数都是一个元组 (value, "label")

    例如,在您的函数中,不必为每个可能的参数数量定义一个函数:

    def multiple_days(startdatetime, enddatetime, index, *temps, windowtitle = "Temperatures over time'):
        # ...
        for temp in temps:
            ax1.plot(frame.index, frame.temp[0], label = temp[1])
        # ...
    

    如果您想通过显式指定临时值的位置来调用函数,当然也可以使用关键字参数 **temps 接受元组列表来执行相同操作。

    【讨论】:

    【解决方案3】:

    可能最简单的方法是只传递temp-label 对的列表。

    def temp10_multiple_days(startdatetime, enddatetime, index, temp_label_pairs,
                             windowtitle = 'Temperatures over time'):
    
        for (temp, label) in temp_label_pairs:
            ax.plot(frame.index, temp, label)
    

    【讨论】:

    • 我正试图让它工作,但我不知道如何格式化它,以便正确地对本地数据帧进行切片。
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    相关资源
    最近更新 更多