如何将一个元组传递给需要一个元组元组的函数

2024-05-21 06:19:25 发布

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

我在为绘图指定自己的x和y值时遇到一些问题。 默认情况下,x和y是数据框列名的组合

例如,var_组合包含:

(('Cerebrum Volume', 'Cerebellum Volume'), ('Cerebrum Volume', 'Cerebellum Surface Area'), ('Cerebellum Volume', 'Cerebellum Surface Area'))

这在单独使用时非常有效,请参见下面的工作代码

col_names = [list(data.columns)[4], list(data.columns)[3], list(data.columns)[1]]
var_combinations = tuple(itertools.combinations(col_names, 2))


def create_plot(xy=var_combinations, logged=False):
    if not logged:
        fig1, axs1 = plt.subplots(1, (len(xy)), figsize=(16, 5))

        for i, (x, y) in enumerate(xy):
            axs1[i].scatter(data[x], data[y], c=taxon.map(colors), edgecolor='k')
            
            axs1[i].set(
                title=f'Primate {xy[i][0]} against\n{xy[i][1]}',
                xlabel=f'{xy[i][0]}',
                ylabel=f'{xy[i][1]}'
            )
    elif logged: .........

create_plot(var_combinations, logged=False)

但是,我希望在调用函数时能够输入自己的变量名,例如:

create_plot(('Cerebellum Surface Area', 'Cerebrum Volume'), ('etc', 'etc'))

当以这种方式调用时,当我点击for循环时,会得到一个ValueError: too many values to unpack (expected 2)。如何解决此问题(并确保标题/轴标签和图形打印工作正常)

csv中的示例数据:

Species ,CerebellumSurfaceArea,CerebrumSurfaceArea,CerebellumVolume ,CerebrumVolume,Source,Taxon,,,,,,
Homo_sapiens,,,111.4,1088,MacLeod et al. (2003),Hominidae,,,,,,
Homo_sapiens,,,138.6,1387.1,,Hominidae,,,,,,
Homo_sapiens,,,132,1176.6,,Hominidae,,,,,,
Homo_sapiens,,,139.8,1264.5,,Hominidae,,,,,,
Homo_sapiens,1590,2038,,,Sereno et al. (2020),Hominidae,,,,,,
Homo_sapiens,1128,,,,Sultan and Braitenberg (1993),Hominidae,,,,,,
Pan_troglodytes,345.545,,52.1,383.22,Ashwell (2020),Hominidae,,,,,,
Pan_troglodytes,,,50.1,343.8,MacLeod et al. (2003),Hominidae,,,,,,

Tags: columnsdatavarareasurfacelistxylogged
1条回答
网友
1楼 · 发布于 2024-05-21 06:19:25
  • 有两个问题,它们仅在尝试向函数发送单个tuple时发生。
    1. xy应该是{}中的{}
      • 它应该类似于(('CerebrumVolume', 'CerebellumVolume '), ('CerebrumVolume', 'CerebellumSurfaceArea'), ('CerebellumVolume ', 'CerebellumSurfaceArea'))
      • 您给它的('Cerebellum Surface Area', 'Cerebrum Volume')未正确解包
      • xy=(('CerebrumVolume', 'CerebellumVolume '),)用于向函数发送单个tuple
    2. 当只有一组元组需要解包时,plt.subplots将创建一个axes而不是一个axes数组
      • 使用squeeze=False,这样即使只有一个axes,也会始终有一个数组,然后使用axes.flatten()展平数组
def create_plot(xy=var_combinations, logged=False):
    
    if not logged:
        fig1, axs1 = plt.subplots(1, (len(xy)), figsize=(16, 5), squeeze=False)  # updated with squeeze=False
        axs1 = axs1.flatten()  # added

        for i, (x, y) in enumerate(xy):
            axs1[i].scatter(data[x], data[y], c=data.Taxon.map(colors), edgecolor='k')
            
            axs1[i].set(
                title=f'Primate {xy[i][0]} against\n{xy[i][1]}',
                xlabel=f'{xy[i][0]}',
                ylabel=f'{xy[i][1]}'
            )


data = pd.read_csv('data.csv', usecols=range(7))
col_names = data.columns.to_numpy()[[4, 3, 1]]
var_combinations = tuple(itertools.combinations(col_names, 2))
colors = {'Hominidae': 'tab:green'}

# fix the way a single tuple is passed to the function
create_plot(xy=(('CerebrumVolume', 'CerebellumVolume '),))

enter image description here

相关问题 更多 >