Пример #1
0
def plotting(df, label):
    '''
    Parameter: DataFrame from query_for_plot which has dates and other labels of interest in columnns;
                label: label of interest to be plotted
    
    Function: plots these with the right type of date on axis and title
    
    '''
    years = mdates.YearLocator()  # every year
    months = mdates.MonthLocator()  # every month
    dates = mdates.DateLocator()  #every date

    list_of_dates = df.dates.tolist()

    No_of_years = list_of_dates[-1].year - list_of_dates[
        0].year  #value in int of difference in years

    fig, ax = plt.subplots(figsize=(12, 7))
    #print(df[label])

    if (No_of_years <= 1):  # if less than 1 year then
        yearsFmt = mdates.DateFormatter(r"%b-%y")
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_major_formatter(yearsFmt)

        ax.plot(df.dates, df[label])
        ax.set_title('Plot of {} from {} to {}'.format(
            label, list_of_dates[0].strftime("%B %Y"),
            list_of_dates[-1].strftime("%B %Y")))
        ax.set_ylabel('{}'.format(label))
        ax.set_ylabel('Time')

        #ax.xaxis.set_minor_locator() #will be useful if many years and we want months to be minor grid location

        datemin = np.datetime64(list_of_dates[0], 'M')
        datemax = np.datetime64(list_of_dates[-1], 'M') + np.timedelta64(
            1, 'M')
        ax.set_xlim(datemin, datemax)

        ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
        ax.grid(True)

        # rotates and right aligns the x labels, and moves the bottom of the
        # axes up to make room for them
        fig.autofmt_xdate()
Пример #2
0
def line_overlay_plot(data: pd.DataFrame, stocks: [],
                      plotDateType: PlotDateType):
    """
    拆线叠加图
    :param data:
    :param stocks:
    :param plotDateType:
    :return:
    """
    time = data.loc[(data["symbol"] == stocks[0])]['time']
    time = timestamp_2_date(time.tolist())
    min_date = time[0]
    max_date = time[-1]

    df = pd.DataFrame(index=time)
    for stock in stocks:
        stock_data = data.loc[(data["symbol"] == stock)]
        # logging.info(timestamp_2_month(stock_data['time']))
        stock_data = list(normalize(stock_data, 'close'))

        logging.info('%s %s', stock, len(stock_data))

        df[stock] = stock_data

    g = sns.lineplot(data=df)

    # X轴刻度设置
    date_locator = None
    if plotDateType == PlotDateType.MONTH:
        date_locator = dates.AutoDateFormatter(dates.MonthLocator())
    elif plotDateType == PlotDateType.WEEK:
        date_locator = dates.AutoDateFormatter(dates.WeekdayLocator())
    elif plotDateType == PlotDateType.DAY:
        date_locator = dates.AutoDateFormatter(dates.DateLocator())

    g.format_xdata = date_locator
    # 鼠标hover 事件
    # plt.gcf().canvas.mpl_connect('motion_notify_event', onpick)
    plt.title('ETF价格叠加图({0} - {1})'.format(date_2_month(min_date),
                                           date_2_month(max_date)))
    plt.legend()
    plt.show()
Пример #3
0
def plotTotals(arguments):
    """plot day totals only"""
    conn = sqlite3.connect('zeverData.db')
    c = conn.cursor()
    sql = buildDateQuery("SELECT  date, SN, E_TODAY FROM inverterData",
                         arguments,
                         post=" ORDER BY date ASC")
    sql += " "
    data = {}
    print(sql)
    for row in c.execute(sql):

        #SELECT  date, SN, PAC_W,  E_TODAY, Status FROM inverterData
        id = row[1]
        if not id in data:
            data[id] = {}
        # print(row[0])
        dt = parser.parse(row[0]).date()
        if not (dt in data[id]) or (data[id][dt] < row[2]):
            data[id][dt] = row[2]  # overwrite with the latest value

    #fig, ax = plt.subplots()
    for id in data:
        xData = [dt for dt in sorted(data[id])]
        ticks = [str(dt) for dt in data[id]]
        yData = [data[id][dt] for dt in sorted(data[id])]
        print(yData)
        print(xData)
        plt.bar(range(len(yData)), yData, align='center')
        plt.xticks(range(len(yData)), ticks)
        #plt.bar(xData, yData)
        print(xData)

    locator = mdates.DateLocator()
    #plt.gca().xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
    #plt.gcf().autofmt_xdate()
    plt.ylabel(('kWh'))
    plt.show()
Пример #4
0
def plot_date_range(df, start_date, end_date=False):
    start_mask = df.index >= start_date
    if end_date:
        end_mask = df.index <= end_date
        display_df = df[start_mask & end_mask].copy()
    else:
        display_df = df[start_mask].copy()

    days = mdates.DateLocator()
    fig, ax = plt.subplots(figsize=(12,8))

    ax.plot(display_df.index, display_df['exchange_rate'])
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
    # ax.xaxis.set_minor_locator(mdates.HourLocator())
    # ax.yaxis.set_label_coords(-0.115,0.5)

    title = np.unique(display_df['from_currency_code'])[0] + ":" + "USD"
    plt.suptitle(title, fontweight='bold', fontsize=19)
    plt.xlabel('Date', fontweight='bold', fontsize=15)
    plt.ylabel("Rate", fontweight='bold', rotation=0, fontsize=15)

    fig.autofmt_xdate()
    plt.show()
def p_create_pic():

    tit = 'Temperature and Depth'

    if not os.path.exists('/home/pi/Desktop/Pictures'):
        os.makedirs('/home/pi/Desktop/Pictures')

    if not os.path.exists('uploaded_files'):
        os.makedirs('uploaded_files')
    n = 0

    try:
        files = []
        files.extend(sorted(glob.glob('/home/pi/Desktop/towifi/*.csv')))

        if not os.path.exists('uploaded_files/mypicfile.dat'):
            open('uploaded_files/mypicfile.dat', 'w').close()

        with open('uploaded_files/mypicfile.dat', 'r') as f:
            content = f.readlines()
            f.close()

        upfiles = [
            line.rstrip('\n')
            for line in open('uploaded_files/mypicfile.dat', 'r')
        ]
        dif_data = list(set(files) - set(upfiles))

        if dif_data == []:
            print 'Standby. When the program detects a probe haul, machine will reboot and show new data.'
            time.sleep(5)
            pass

##################################
##################################
        dif_data.sort(key=os.path.getmtime)
        for fn in dif_data:

            fn2 = fn

            if not os.path.exists('/home/pi/Desktop/Pictures/' +
                                  fn.split('/')[-1][6:14]):
                os.makedirs('/home/pi/Desktop/Pictures/' +
                            fn.split('/')[-1][6:14])
            df = pd.read_csv(fn,
                             sep=',',
                             skiprows=7,
                             parse_dates={'datet': [1]},
                             index_col='datet',
                             date_parser=parse2)  #creat a new Datetimeindex
            df2 = df
            df2['Depth (m)'] = [x * (-0.5468) for x in df2['Depth (m)'].values]

            if len(df2) < 5:
                continue

            meantemp = round(np.mean(df['Temperature (C)']), 2)
            fig = plt.figure()
            ax1 = fig.add_subplot(211)
            ax2 = fig.add_subplot(212)
            time_df2 = gmt_to_eastern(df2.index)
            time_df = gmt_to_eastern(df.index)

            ax1.plot(
                time_df,
                df['Temperature (C)'],
                'b',
            )
            ax1.set_ylabel('Temperature (Celius)')
            ax1.legend(['temp', 'in the water'])
            try:
                if max(df.index) - min(
                        df.index) > Timedelta('0 days 04:00:00'):
                    ax1.xaxis.set_major_locator(
                        dates.DateLocator(
                            interval=(max(df.index) - min(df.index)).seconds /
                            3600 / 12))  # for hourly plot
                    ax2.xaxis.set_major_locator(
                        dates.DateLocator(
                            interval=(max(df.index) - min(df.index)).seconds /
                            3600 / 12))  # for hourly plot
                else:
                    ax1.xaxis.set_major_locator(
                        dates.DateLocator(
                            interval=(max(df.index) - min(df.index)).seconds /
                            3600 / 4))  # for hourly plot
                    ax2.xaxis.set_major_locator(
                        dates.DateLocator(
                            interval=(max(df.index) - min(df.index)).seconds /
                            3600 / 4))  # for hourly plot
            except:
                print ' '
            clim = getclim(
            )  # extracts climatological values at this place and yearday
            if isnan(clim):
                txt = 'mean temperature =' + str(round(
                    meantemp, 1)) + 'F (No Climatology here.)'
            else:
                txt = 'mean temperature =' + str(round(
                    c2f(meantemp), 1)) + 'F Climatology =' + str(
                        round(c2f(clim), 1)) + 'F'
            ax1.text(0.9,
                     0.15,
                     txt,
                     verticalalignment='bottom',
                     horizontalalignment='right',
                     transform=ax1.transAxes,
                     color='green',
                     fontsize=15)
            ax1.grid()
            ax12 = ax1.twinx()
            ax12.set_title(tit)
            ax12.set_ylabel('Fahrenheit')
            ax12.set_xlabel('')
            ax12.set_ylim(
                np.nanmin(df['Temperature (C)'].values) * 1.8 + 30,
                np.nanmax(df['Temperature (C)'].values) * 1.8 + 36)

            ax2.plot(time_df2,
                     df2['Depth (m)'],
                     'b',
                     label='Depth',
                     color='green')
            ax2.legend()
            ax2.invert_yaxis()
            ax2.set_ylabel('Depth(Fathom)')
            ax2.set_ylim(
                np.nanmin(df2['Depth (m)'].values) * 1.05,
                np.nanmax(df2['Depth (m)'].values) * 0.95)
            ax2.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
            ax2.grid()

            ax22 = ax2.twinx()
            ax22.set_ylabel('Depth(feet)')
            ax22.set_ylim(
                np.nanmax(df2['Depth (m)'].values) * 6 * 0.95,
                np.nanmin(df2['Depth (m)'].values) * 6 * 1.05)
            ax22.invert_yaxis()

            plt.gcf().autofmt_xdate()
            ax2.set_xlabel('TIME ' + time_df[0].astimezone(
                pytz.timezone('US/Eastern')).strftime('%m/%d/%Y %H:%M:%S') +
                           ' - ' +
                           time_df[-1].astimezone(pytz.timezone(
                               'US/Eastern')).strftime('%m/%d/%Y %H:%M:%S'))
            plt.savefig('/home/pi/Desktop/Pictures/' +
                        fn.split('/')[-1][6:14] + '/' +
                        fn.split('/')[-1][15:21] + '.png')
            plt.close()

        a = open('uploaded_files/mypicfile.dat', 'r').close()

        a = open('uploaded_files/mypicfile.dat', 'a+')

        [a.writelines(i + '\n') for i in dif_data]
        a.close()

        print 'New data successfully downloaded. Plot will appear.'
        return

    except:
        return