python类DateFormatter()的实例源码

plotter.py 文件源码 项目:trafficjuggler 作者: Pavel-Polyakov 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def getFigureByXY(x,y):
    ylabel='\nOutput, MBps'
    fig = Figure(figsize=(16,6), dpi=120)
    axis = fig.add_subplot(1, 1, 1)
    axis.plot(x, y, color='#2b8ef9')
    axis.fill_between(x,y, facecolor='#2b8ef9')
    axis.grid(True)
    axis.set_ylim(bottom=0)
    axis.set_ylabel(ylabel)
    # axis.set_xlabel('\n%s - %s' % (x[0],x[-1]))
    axis.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))
    axis.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,1)))
    fig.autofmt_xdate()
    fig.set_facecolor('white')
    return fig
plotter.py 文件源码 项目:DGP 作者: DynamicGravitySystems 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def generate_subplots(self, rows: int) -> None:
        """Generate vertically stacked subplots for comparing data"""
        # TODO: Experimenting with generating multiple plots, work with Chris on this class
        # def set_x_formatter(axes):
        #     print("Xlimit changed")
        #     axes.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S'))

        # Clear any current axes first
        self._axes = []
        for i in range(rows):
            if i == 0:
                sp = self.figure.add_subplot(rows, 1, i+1)  # type: Axes
            else:  # Share x-axis with plot 0
                sp = self.figure.add_subplot(rows, 1, i + 1, sharex=self._axes[0])  # type: Axes

            sp.grid(True)
            sp.name = 'Axes {}'.format(i)
            # sp.callbacks.connect('xlim_changed', set_x_formatter)
            self._axes.append(sp)
            i += 1

        self.compute_initial_figure()
pyGrav_main.py 文件源码 项目:pyGrav 作者: basileh 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def setPlot(self,axe,seriex,seriey,seriex_selec,seriey_selec,serie_type,serie_unit):
        """
        plot a single station
        """
        axe.clear()
        axe.grid(True)
        if serie_type=='gravity' and seriey_selec:
            mean_g=np.mean(seriey_selec)
            axe.plot([seriex[0],seriex[len(seriex)-1]],[mean_g,mean_g],'o-',color='b',label=serie_type)        

        axe.plot(seriex,seriey,'o-',color='k',label=serie_type)
        axe.plot(seriex_selec,seriey_selec,'o-',color='b',label=serie_type)            
        axe.set_ylabel(serie_unit, size='x-small')
        axe.set_title(serie_type, size='x-small')
        labels = axe.get_xticklabels() + axe.get_yticklabels()
        for label in labels:
            label.set_size('x-small') 
        xfmt = md.DateFormatter('%H:%M')
        axe.xaxis.set_major_formatter(xfmt)            
        plt.setp(axe.get_xticklabels(), rotation=30, horizontalalignment='right')              
        self.canvas.draw()
plots.py 文件源码 项目:ee-atmcorr-timeseries 作者: samsammurphy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_timeseries(DF, ax, name, startDate, stopDate, ylim=False):
    """
    plots timeseries graphs
    """

    # original time series
    ax.plot(DF[name],color='#1f77b4')
    ax.set_ylabel(name)
    ax.set_ylim(ylim)
    ax.set_xlim(pd.datetime.strptime(startDate,'%Y-%m-%d'),\
                pd.datetime.strptime(stopDate,'%Y-%m-%d'))

    # boxcar average
    ax.plot(DF[name].rolling(180).mean(),color='red')

    # make the dates exact
    ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
interval.py 文件源码 项目:err-stackdriver 作者: GoogleCloudPlatform 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, tick_minutes, alignment_period=None,
                 per_series_aligner=None,
                 major_formatter=mdates.DateFormatter('%H:%M')):
        """Visual configuration for the time interval to display in a graph.

        Args:
          major_tick_minutes: (int) The number of minutes between each tick.
          alignment_period: (Optional str) E.g., "120s". The size of each point's
            bucket of data. If None is provided, each point in the graph will refer
            to a moment in time rather than a bucket of time. Min is 60s.
          per_series_aligner: (Optional str) E.g., "ALIGN_MAX".  The aligner to use
            for each series.
          major_formatter: (Optional matplotlib.Formatter) The formatter for each
            major tick mark's x-axis time label. Defaults to one that turns an X point
            into HH:MM e.g., "17:35".
        """
        self.tick_minutes = tick_minutes
        self.alignment_period = alignment_period
        self.per_series_aligner = per_series_aligner
        self.major_formatter = major_formatter
main.py 文件源码 项目:finance-hacking 作者: wellsjo 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def graphRawFX():
    date, bid, ask = np.loadtxt('data/GBPUSD1d.txt',
            unpack=True,
            delimiter=',',
            converters={0: mdates.strpdate2num('%Y%m%d%H%M%S')}
            )
    fig = plt.figure(figsize=(10,7))
    ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40)
    ax1.plot(date, bid)
    ax1.plot(date, ask)
    plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax1_2 = ax1.twinx()
    ax1_2.fill_between(date, 0, (ask-bid), facecolor='g', alpha=.3)

    plt.subplots_adjust(bottom=.23)

    plt.grid(True)
    plt.show()
tools.py 文件源码 项目:WaveletQuotes 作者: JobyKK 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def showResult(date, scales, power, time_scale, window, file_name):
    # y_ticks = np.arange(0, 15, 2)
    import matplotlib.ticker as mticker
    import matplotlib.dates as mdates
    fig, ax = plt.subplots()
    ax.xaxis.set_major_locator(YearLocator(time_scale))
    # ax.set_yticks(y_ticks)
    ax.xaxis.set_major_locator(mticker.MaxNLocator(5))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

    ax.contourf(date, scales, power, 100)
    # ax.set_yscale('log')
    print("Wavelet saved to", file_name)
    fig.savefig(file_name)
    # fig.show()
    # fig.waitforbuttonpress()
siamchart.py 文件源码 项目:trading-stock-thailand 作者: adminho 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plotCandlestick(symbol, dates, title="Selected data"):  
    quotes = loadStockQuotes(symbol, dates)     

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays = DayLocator()                  # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
    dayFormatter = DateFormatter('%d')      # e.g., 12

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick_ohlc(ax, quotes, width=0.6)

    ax.xaxis_date()
    ax.autoscale_view()
    ax.set_title(title)
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    plt.show()
pandas_reader.py 文件源码 项目:trading-stock-thailand 作者: adminho 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plotCandlestick(symbol, startdate, enddate, title="Selected data"): 
    quotes = loadStockQuotes(symbol, startdate, enddate)        
    print(quotes)
    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
#   dayFormatter = DateFormatter('%d')    # e.g., 12

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick_ohlc(ax, quotes, width=0.6)

    ax.xaxis_date()
    ax.autoscale_view()
    ax.set_title(title)
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    plt.show()
utilgraph.py 文件源码 项目:trading-stock-thailand 作者: adminho 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plotCandlestick(symbol, start_index, end_index, title="Selected data"):
    dates = pd.date_range(start_index, end_index)   
    quotes = utl.loadStockQuotes(symbol, dates)     

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays = DayLocator()                  # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
    dayFormatter = DateFormatter('%d')      # e.g., 12

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick_ohlc(ax, quotes, width=0.6)

    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    plt.show()
markov_stock_analysis v2-4.py 文件源码 项目:markov_stock_analysis 作者: nb5hd 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def percent_change_as_time_plot(adjusted_df, security):
    """
    This function visualizes the percentage change data as a time series plot.

    :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
    :param security: <SecurityInfo class> Holds information about the requested security
    """

    pct_change_list = adjusted_df['Percentage Change'].tolist()
    date_list = adjusted_df.index.values
    fig, ax = plt.subplots()
    ax.plot(date_list, pct_change_list)
    plt.xlabel("Dates")
    plt.ylabel("Percentage change from last period")
    if security.get_period() == "none":
        plt.title("Percentage change in " + security.get_name(), y=1.03)
    else:
        plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.yaxis.set_minor_locator(MultipleLocator(1))
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.autoscale_view()
    fig.autofmt_xdate()

    plt.show()
markov_stock_forecasting_model_v2-5.py 文件源码 项目:markov_stock_analysis 作者: nb5hd 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def percent_change_as_time_plot(adjusted_df, security):
    """
    This function visualizes the percentage change data as a time series plot.

    :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
    :param security: <SecurityInfo class> Holds information about the requested security
    """

    pct_change_list = adjusted_df['Percentage Change'].tolist()
    date_list = adjusted_df.index.values
    fig, ax = plt.subplots()
    ax.plot(date_list, pct_change_list)
    plt.xlabel("Dates")
    plt.ylabel("Percentage change from last period")
    if security.get_period() == "none":
        plt.title("Percentage change in " + security.get_name(), y=1.03)
    else:
        plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.yaxis.set_minor_locator(MultipleLocator(1))
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.autoscale_view()
    fig.autofmt_xdate()

    plt.show()
markov_stock_analysis v2-2.py 文件源码 项目:markov_stock_analysis 作者: nb5hd 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def percent_change_as_time_plot(adjusted_df):
    """
    This function visualizes the percentage change data as a time series plot.

    :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
    """

    pct_change_list = adjusted_df['Percentage Change'].tolist()
    date_list = adjusted_df.index.values
    fig, ax = plt.subplots()
    ax.plot(date_list, pct_change_list)
    #ax.plot(date_list, adjusted_df["Adjusted Close"])
    plt.xlabel("Years")
    plt.ylabel("Percentage change from last week")
    plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.yaxis.set_minor_locator(MultipleLocator(1))
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.autoscale_view()
    fig.autofmt_xdate()

    plt.show()
markov_stock_analysis.py 文件源码 项目:markov_stock_analysis 作者: nb5hd 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def percent_change_as_time_plot(adjusted_df):
    """
    This function visualizes the percentage change data as a time series plot.

    :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
    """

    pct_change_list = adjusted_df['Percentage Change'].tolist()
    date_list = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in adjusted_df['Date'].tolist()]
    fig, ax = plt.subplots()
    ax.plot(date_list, pct_change_list)
    plt.xlabel("Years")
    plt.ylabel("Percentage change from last week")
    plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.yaxis.set_minor_locator(MultipleLocator(1))
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.autoscale_view()
    fig.autofmt_xdate()

    plt.show()
markov_stock_analysis v2-3.py 文件源码 项目:markov_stock_analysis 作者: nb5hd 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def percent_change_as_time_plot(adjusted_df, security):
    """
    This function visualizes the percentage change data as a time series plot.

    :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
    :param security: <SecurityInfo class> Holds information about the requested security
    """

    pct_change_list = adjusted_df['Percentage Change'].tolist()
    date_list = adjusted_df.index.values
    fig, ax = plt.subplots()
    ax.plot(date_list, pct_change_list)
    plt.xlabel("Dates")
    plt.ylabel("Percentage change from last period")
    if security.get_period() == "none":
        plt.title("Percentage change in " + security.get_name(), y=1.03)
    else:
        plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.yaxis.set_minor_locator(MultipleLocator(1))
    ax.fmt_xdata = DateFormatter('%Y-%m-%d')
    ax.autoscale_view()
    fig.autofmt_xdate()

    plt.show()
TwitterAxe.py 文件源码 项目:StockTalk3 作者: xenu256 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def savePlot(self, name, width=6, height=4.5):
        timestamps = []
        sentiment = []
        tweets = []
        for data_point in self.timeSeries:
            timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S'))
            sentiment.append(data_point["SENTIMENT"])
            tweets.append(data_point["TWEETS"])

        # Plot setup
        ax1 = plt.figure(figsize=(width, height)).add_subplot(111)
        ax1.spines["top"].set_visible(False)
        ax1.get_xaxis().tick_bottom()
        ax1.get_yaxis().tick_left()
        ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M'))
        lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment")
        plt.yticks(fontsize=8)
        plt.ylim(ymin=-1, ymax=1)
        plt.xticks(rotation=50, fontsize=8)
        ax2 = ax1.twinx()
        lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets")
        ax2.margins(0.05)
        plt.yticks(fontsize=8)

        # Labeling
        ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6)
        ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1)
        ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15)
        plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08)
        plt.ylim(ymin=0)
        plt.tight_layout()
        file_name = join(BASE_PATH, "outputs", name+".png")
        plt.savefig(file_name)
        print("Saved plot {}".format(file_name))
TwitterAxe.py 文件源码 项目:StockTalk3 作者: xenu256 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def showPlot(self):
        timestamps = []
        sentiment = []
        tweets = []
        for data_point in self.timeSeries:
            timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S'))
            sentiment.append(data_point["SENTIMENT"])
            tweets.append(data_point["TWEETS"])

        # Plot setup
        ax1 = plt.figure(figsize=(6, 4.5)).add_subplot(111)
        ax1.spines["top"].set_visible(False)
        ax1.get_xaxis().tick_bottom()
        ax1.get_yaxis().tick_left()
        ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M'))
        lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment")
        plt.yticks(fontsize=8)
        plt.ylim(ymin=-1, ymax=1)
        plt.xticks(rotation=50, fontsize=8)
        ax2 = ax1.twinx()
        lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets")
        ax2.margins(0.05)
        plt.yticks(fontsize=8)

        # Labeling
        ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6)
        ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1)
        ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15)
        plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08)
        plt.ylim(ymin=0)
        plt.tight_layout()
        plt.show()
Funstuff.py 文件源码 项目:Luna 作者: Moonlington 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plotjoins(self, ctx):
        """Plots the joindates of everyone in the server"""
        sm = ctx.message.server.members
        x = sorted([m.joined_at for m in sm])
        y = range(len(x))
        plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
        plt.plot(x, y)
        plt.gcf().autofmt_xdate()
        plt.title("Plot of joins from {}".format(ctx.message.server.name))
        buf = BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        await self.bot.upload(buf, filename='plot.png')
        buf.close()
        plt.close()
graph.py 文件源码 项目:raiden 作者: raiden-network 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plot_date_axis(axes):
    from matplotlib import dates

    date_fmt = dates.DateFormatter('%d/%b')
    hour_fmt = dates.DateFormatter('%H:%M')

    # TODO: set xaxis minor interval dynamically

    axes.xaxis.set_major_locator(dates.DayLocator(interval=1))
    axes.xaxis.set_major_formatter(date_fmt)
    # less than 5 days and interval of 3 is okay
    axes.xaxis.set_minor_locator(dates.HourLocator(interval=4))
    axes.xaxis.set_minor_formatter(hour_fmt)
    axes.xaxis.set_tick_params(which='major', pad=15)
live_graph_clock.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, sessions, context, time_skew=pd.Timedelta('0s')):

        global mdates, plt  # TODO: Could be cleaner
        import matplotlib.dates as mdates
        from matplotlib import pyplot as plt
        from matplotlib import style

        self.sessions = sessions
        self.time_skew = time_skew
        self._last_emit = None
        self._before_trading_start_bar_yielded = True
        self.context = context
        self.fmt = mdates.DateFormatter('%Y-%m-%d %H:%M')

        style.use('dark_background')

        fig = plt.figure()
        fig.canvas.set_window_title('Enigma Catalyst: {}'.format(
            self.context.algo_namespace))

        self.ax_pnl = fig.add_subplot(311)

        self.ax_custom_signals = fig.add_subplot(312, sharex=self.ax_pnl)

        self.ax_exposure = fig.add_subplot(313, sharex=self.ax_pnl)

        if len(context.minute_stats) > 0:
            self.draw_pnl()
            self.draw_custom_signals()
            self.draw_exposure()

        # rotates and right aligns the x labels, and moves the bottom of the
        # axes up to make room for them
        fig.autofmt_xdate()
        fig.subplots_adjust(hspace=0.5)

        plt.tight_layout()
        plt.ion()
        plt.show()
RpiTempmonGraph.py 文件源码 项目:raspberrypi_tempmon 作者: gavinlyonsrepo 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def graph_log_data(self, destlog):
        """draw a  graph of pi GPU CPU from logdata"""
        #define lists to hold data from logfile
        timelist = []
        cpulist = []
        gpulist = []

        #get data from file and put into lists
        mypath = destlog + "/" + "log.txt"
        if os.path.isfile(mypath):
            with open(mypath, 'r') as myfile:
                for line in myfile:
                    if "TS" in line:
                        timelist.append(line[5:-1])
                    if "CPU" in line:
                        cpulist.append(line[18:20])
                    if "GPU" in line:
                        gpulist.append(line[18:20])
        else:
            print("Log file not found at {}".format(mypath))
            return 1
        #parse dates format
        mydates = [dateutil.parser.parse(s) for s in timelist]
        #make graph matplotlib from logfile
        plt.xticks(rotation=25)
        plt.subplots_adjust(bottom=0.2)
        axisx = plt.gca()
        axisx.set_xticks(mydates)
        xfmt = md.DateFormatter('%m/%d %H:%M')
        axisx.xaxis.set_major_formatter(xfmt)
        axisx.xaxis.label.set_color('red')
        axisx.yaxis.label.set_color('red')
        plt.plot(mydates, cpulist, label='CPU', color='green', marker='x')
        plt.plot(mydates, gpulist, label='GPU', marker='*')
        plt.xlabel('Date time stamp (DD-MM HH:MM)')
        plt.ylabel('Temperature (degrees)')
        plt.title('ARM CPU and GPU temperature of Raspberry Pi 3', color='green')
        plt.legend(loc='upper right',
                   fancybox=True, shadow=True)
        plt.grid(True)
        plt.show()
plotter.py 文件源码 项目:DGP 作者: DynamicGravitySystems 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _on_xlim_changed(ax: Axes):
        ax.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S'))
plotting.py 文件源码 项目:DGP 作者: DynamicGravitySystems 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def generate_subplots(self, x, *args):
        def _on_xlims_change(axes):
            # reset the x-axis format when the plot is resized
            axes.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S'))

        i = 0
        numplots = len(args)
        fig = plt.figure()

        self.cidclick = fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.cidrelease = fig.canvas.mpl_connect('button_release_event', self.onrelease)
        self.cidmotion = fig.canvas.mpl_connect('motion_notify_event', self.onmotion)

        for arg in args:
            if i == 0:
                a = fig.add_subplot(numplots, 1, i+1)
            else:
                a = fig.add_subplot(numplots, 1, i+1, sharex=self.axes[0])

            a.plot(x.to_pydatetime(), arg)
            a.fmt_xdata = DateFormatter('%H:%M:%S')
            a.grid(True)
            a.callbacks.connect('xlim_changed', _on_xlims_change)
            self.axes.append(a)
            i += 1

        if not mpl.is_interactive():
            fig.show()

        self.figure = fig
        plt.show()

    # TO DO: Consider PatchCollection for rectangles.
ts_tool.py 文件源码 项目:pyktrader2 作者: harveywwu 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_price_series(df, ts_lab1, ts_lab2):
    #months = mdates.MonthLocator()  # every month
    fig, ax = plt.subplots()
    ax.plot(df.index, df[ts_lab1], label=ts_lab1)
    ax.plot(df.index, df[ts_lab2], label=ts_lab2)
    #ax.xaxis.set_major_locator(months)
    #ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    ax.grid(True)
    fig.autofmt_xdate()
    plt.xlabel('Month/Year')
    plt.ylabel('Price ($)')
    plt.title('%s and %s Daily Prices' % (ts_lab1, ts_lab2))
    plt.legend()
    plt.show()
ts_tool.py 文件源码 项目:pyktrader2 作者: harveywwu 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot_series(ts):
    #months = mdates.MonthLocator()  # every month
    fig, ax = plt.subplots()
    ax.plot(ts.index, ts, label=ts.name)
    #ax.xaxis.set_major_locator(months)
    #ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    #ax.set_xlim(datetime.datetime(2012, 1, 1), datetime.datetime(2013, 1, 1))
    ax.grid(True)
    fig.autofmt_xdate()
    plt.xlabel('Month/Year')
    plt.ylabel('Price ($)')
    plt.title('Residual Plot')
    plt.legend()
    plt.plot(ts)
    plt.show()
plottools.py 文件源码 项目:finance_news_analysis 作者: pskun 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def plot_date_line_and_vline(
        line_values,
        line_dates,
        vline_dates = [],
        line_label = [],
        line_color = []):
    ''' line_values could be 1d or nd arrays '''
    if len(line_label) == 0:
        if len(line_values.shape) == 1:
            line_label = ['line']
        else:
            line_label_coll = ['line1', 'line2', 'line3', 'line4', 'line5', 'line6', 'line7', 'line8']
            line_label = line_label_coll[0:line_values.shape[1]]

    if len(line_color) == 0:
        if len(line_values.shape) == 1:
            line_color = ['CornflowerBlue']
        else:
            line_color_coll = ['Blue', 'Green', 'Red', 'DarkTurquoise', 'Chocolate', 'CadetBlue', 'IndianRed', 'Orange']
            line_color = line_color_coll[0:line_values.shape[1]]

    line_dtdates = [get_datetime_date(x) for x in line_dates]
    vline_dtdates = [get_datetime_date(x) for x in vline_dates]
    (fig, ax) = plt.subplots()
    if len(line_values.shape) == 1:
        ax.plot_date(line_dtdates, line_values, '-', label = line_label[0], color = line_color[0])
    else:
        for i in xrange(line_values.shape[1]):
            ax.plot_date(line_dtdates, line_values[:, i], '-', label = line_label[i], color = line_color[i])
    for vldate in vline_dtdates:
        ax.axvline(vldate)
    ax.xaxis.set_major_formatter(plt_dates.DateFormatter('%Y-%m-%d'))
    def ydata(y): return '$%1.2f'%y
    ax.fmt_xdata = plt_dates.DateFormatter('%Y-%m-%d')
    ax.fmt_ydata = ydata
    ax.grid(True)
    # show
    fig.autofmt_xdate()
    plt.legend()
    plt.show()
chart.py 文件源码 项目:rapidpythonprogramming 作者: thecount12 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def gData(stock): 
    stockFile=stock+".txt"
    date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True,converters={0: mdates.strpdate2num('%Y%m%d')})
    fig=plt.figure() 
    ax1=plt.subplot(1,1,1) # how much by how much by 
    ax1.plot(date,openp) 
    ax1.plot(date,highp) 
    ax1.plot(date,lowp) 
    ax1.plot(date,closep)
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    for label in ax1.xaxis.get_ticklabels(): 
        label.set_rotation(45)
    plt.show()
graph.py 文件源码 项目:rapidpythonprogramming 作者: thecount12 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def graphData(stock):
        stockFile=stock+".txt"

        date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True,
                        converters={0: mdates.strpdate2num('%Y%m%d')})
        fig=plt.figure()
        ax1=plt.subplot(1,1,1) # how much by how much by 
        ax1.plot(date,openp)
        ax1.plot(date,highp)
        ax1.plot(date,lowp)
        ax1.plot(date,closep)

        #pretty it up
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

        # rotate
        for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)


        plt.show()
graphperfmetrics.py 文件源码 项目:PyU4V 作者: ciarams87 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def main():
    array_metrics=get_array_kpi()
    perfdatalist=array_metrics.get('perf_data')
    hostiolist = []
    dtstimelist = []
    readresponselist =[]
    print (perfdatalist)
    for perf_host in perfdatalist:
        hostiolist.append(perf_host.get('HostIOs'))
        readresponselist.append(perf_host.get('ReadResponseTime'))
        epochtime=(perf_host.get ('timestamp'))
        dtstime = round(epochtime/1000)
        dtstimelist.append(dtstime)

    dateconv=np.vectorize(dt.datetime.fromtimestamp)
    convtimelist =(dateconv(dtstimelist))
    # print(convtimelist)
    fig, ax = plt.subplots(1)
    fig.autofmt_xdate()
    xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
    ax.xaxis.set_major_formatter(xfmt)
    plt.plot_date(convtimelist,hostiolist,'-')
    plt.plot_date(convtimelist, readresponselist, '-')
    plt.legend(['HostIOs', 'ReadResponseTime'], loc='upper left')
    plt.subplots_adjust(bottom=0.1)
    plt.xticks(rotation=25)
    plt.ylabel('Host IOs')
    plt.xlabel('Time')
    plt.title('Host IOs and Read Response times over the last Hour')
    plt.show()
find_tgt_info.py 文件源码 项目:jwst_gtvt 作者: spacetelescope 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_single_instrument(ax, instrument_name, t, min_pa, max_pa):

    min_pa = np.array(min_pa)
    max_pa = np.array(max_pa)
    t = np.array(t)

    if np.any(min_pa > max_pa):
        minpa_lt_maxpa = min_pa < max_pa
        minpa_gt_maxpa = min_pa > max_pa

        max_pa_upper = np.copy(max_pa)
        min_pa_upper = np.copy(min_pa)
        max_pa_upper[minpa_gt_maxpa] = 360
        max_pa_upper[minpa_lt_maxpa] = np.nan
        min_pa_upper[minpa_lt_maxpa] = np.nan

        max_pa_lower = np.copy(max_pa)
        min_pa_lower = np.copy(min_pa)
        min_pa_lower[minpa_gt_maxpa] = 0
        max_pa_lower[minpa_lt_maxpa] = np.nan
        min_pa_lower[minpa_lt_maxpa] = np.nan


        max_pa[minpa_gt_maxpa] = np.nan
        min_pa[minpa_gt_maxpa] = np.nan

        ax.fill_between(t, min_pa_upper, max_pa_upper, facecolor='.7', edgecolor='.7', lw=2)
        ax.fill_between(t, min_pa_lower, max_pa_lower, facecolor='.7', edgecolor='.7', lw=2)
        ax.fill_between(t, min_pa, max_pa, edgecolor='.7', facecolor='.7', lw=2)
        ax.set_ylabel("Available Position Angle (Degree)")
        ax.set_title(instrument_name)
        ax.fmt_xdata = DateFormatter('%Y-%m-%d')    


    else:
        ax.fill_between(t, min_pa, max_pa, edgecolor='none', facecolor='.7')
        ax.set_ylabel("Available Position Angle (Degree)")
        ax.set_title(instrument_name)
        ax.fmt_xdata = DateFormatter('%Y-%m-%d')


问题


面经


文章

微信
公众号

扫码关注公众号