首页 > 解决方案 > if else语句python在函数中使用绘图参数

问题描述

我的函数中有一个 if else 语句,它没有按照我想要的方式工作。请注意,我仍在学习 python 和所有编程。

我有一个功能来定义一个情节。想法是创建一个用于数据分析的大型 python 存储库。编辑:我添加了一个工作换班数据框供您尝试

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
#import numpy as np
#import os
#import dir_config as dcfg
#import data_config as datacfg
import matplotlib.dates as md
#import cartopy.crs as ccrs

data = {'dates': [20200901,20200902,20200903,20200904,20200905,20200906,20200907,20200908,20200909,20200910],
        'depth': [1,2,3,4,5,6,7,8,9,10],
        'cond': [30.1,30.2,30.3,30.6,31,31.1,31.0,31.4,31.1,30.9]
        }
df = pd.DataFrame(data, columns = ['dates', 'depth', 'cond'])
df['pd_datetime'] = pd.to_datetime(df['dates'])
 

def ctd_plots_timeseries(time=[],cond=[], sal =[], temp=[], depth=[], density=[]):
    #-----------
    # CONDUCTIVITY PLOT
    #-----------
    
    if cond == []:
        print("there is no data for cond")
        pass
    else:
        plt.scatter(time,depth,s=15,c=cond,marker='o', edgecolor='none')
        plt.show()

    #-----------
    # SALINITY (PSU) PLOT: I do not want this to plot at all due to its parameter being 'empty' in the function when called
    #-----------
    if sal == []:
        print('there is no salinity data')
        pass
    else:
        plt.scatter(time,depth,s=15,c=sal,marker='o', edgecolor='none')
        plt.show()


ctd_plots_timeseries(depth = df['depth'], time = df['pd_datetime'], cond = df['cond'])

这里的想法是,如果 cond 值中没有数据,请pass不要显示该图。然而,每当我运行它时,情节就会显示,甚至认为没有数据。

当我调用我输入的函数时plot_timeseries(time=time_data, depth=depth_data temp=temp_data)

我的目标是仅显示此示例中的临时数据,而不是没有变量的条件图。

我试过的是

if cond != []:
        plotting code
        plt.show()
else:
        print('there is no cond data')
        pass

plotting code
if cond == []:
    print('no cond data')
    pass
else:
    plt.show()

无济于事。

请注意,此函数中还有 4 个其他图我想做同样的事情。感谢这个社区可以给我的任何见解。

更新:我将函数中的条件更改为def ctd_plots_timeseries(time=0,cond=0, sal =0, temp=0, depth=0, density=0): ,然后将条件语句更改为

if cond != 0:
    graphing code
else:
    print('no data here')

我收到以下错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

标签: python-3.xmatplotlibif-statementplottime-series

解决方案


我已经简化了。试试看:

def plots_timeseries(cond = []): # Single argument for clarity
    if not cond:
        print('there is no cond value')
    else:
        print('There is cond')

plots_timeseries()
# there is no cond value

推荐阅读