コード例 #1
0
async def plot_karma(karma_dict: Dict[str, List[KarmaChange]]) -> (str, str):
    # Error if there's no input data
    if len(karma_dict) == 0:
        return "", ""

    # Matplotlib preamble
    plt.clf()
    plt.rcParams.update({"figure.autolayout": True})
    fig, ax = plt.subplots(figsize=(8, 6))

    # Get the earliest and latest karma values fo
    earliest_karma = utc.localize(datetime.utcnow()).astimezone(
        timezone("Europe/London")
    )
    latest_karma = utc.localize(datetime(1970, 1, 1)).astimezone(
        timezone("Europe/London")
    )
    for key, changes in karma_dict.items():
        earliest_karma = (
            changes[0].local_time
            if changes[0].local_time < earliest_karma
            else earliest_karma
        )
        latest_karma = (
            changes[-1].local_time
            if changes[-1].local_time >= latest_karma
            else latest_karma
        )

    karma_timeline = latest_karma - earliest_karma

    # Determine the right graph tick positioning
    if karma_timeline <= timedelta(hours=1):
        date_format = DateFormatter("%H:%M %d %b %Y")
        date_locator_major = MinuteLocator(interval=15)
        date_locator_minor = MinuteLocator()
    elif karma_timeline <= timedelta(hours=6):
        date_format = DateFormatter("%H:%M %d %b %Y")
        date_locator_major = HourLocator()
        date_locator_minor = MinuteLocator(interval=15)
    elif karma_timeline <= timedelta(days=14):
        date_format = DateFormatter("%d %b %Y")
        date_locator_major = DayLocator()
        date_locator_minor = HourLocator(interval=6)
    elif karma_timeline <= timedelta(days=30):
        date_format = DateFormatter("%d %b %Y")
        date_locator_major = WeekdayLocator()
        date_locator_minor = DayLocator()
    elif karma_timeline <= timedelta(days=365):
        date_format = DateFormatter("%B %Y")
        date_locator_major = MonthLocator()
        date_locator_minor = WeekdayLocator(interval=2)
    else:
        date_format = DateFormatter("%Y")
        date_locator_major = YearLocator()
        date_locator_minor = MonthLocator()

    # Transform the karma changes into plottable values
    for karma, changes in karma_dict.items():
        scores = [k.score for k in changes]
        time = date2num([k.local_time for k in changes])

        # Plot the values
        ax.xaxis.set_major_locator(date_locator_major)
        ax.xaxis.set_minor_locator(date_locator_minor)
        ax.xaxis.set_major_formatter(date_format)
        ax.grid(b=True, which="minor", color="0.9", linestyle=":")
        ax.grid(b=True, which="major", color="0.5", linestyle="--")
        ax.set(
            xlabel="Time",
            ylabel="Karma",
            xlim=[
                time[0] - ((time[-1] - time[0]) * 0.05),
                time[-1] + ((time[-1] - time[0]) * 0.05),
            ],
        )
        (line,) = ax.plot_date(time, scores, "-", xdate=True)
        line.set_label(karma)

    # Create a legend if more than  1 line and format the dates
    if len(karma_dict.keys()) > 1:
        ax.legend()
    fig.autofmt_xdate()

    # Save the file to disk and set the right permissions
    filename = (
        "".join(karma_dict.keys())
        + "-"
        + str(hex(int(datetime.utcnow().timestamp()))).lstrip("0x")
        + ".png"
    ).replace(" ", "")
    path = CONFIG.FIG_SAVE_PATH / filename

    fig.savefig(path, dpi=240, transparent=False)
    os.chmod(path, 0o644)

    return filename, path
コード例 #2
0
from matplotlib.dates import DateFormatter
from matplotlib.dates import DayLocator
from matplotlib.dates import MonthLocator
from matplotlib.finance import quotes_historical_yahoo_ochl
from matplotlib.finance import candlestick_ochl

import sys
from datetime import date
import matplotlib.pyplot as plt

today = date.today()
start = (today.year - 1, today.month, today.day)
# 创建定位器
alldays = DayLocator()
months = MonthLocator()
month_formatter = DateFormatter("%b %Y")  #创建格式化日期

symbol = "DISH"

if len(sys.argv) == 2:
    symbol = sys.argv[1]
quotes = quotes_historical_yahoo_ochl(symbol, start, today)

# 创建一个matplotlib的figure,这是一个绘图组件的顶层容器
fig = plt.figure()
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(month_formatter)
candlestick_ochl(ax, quotes=quotes)
コード例 #3
0
ch4ay = N.asarray(ch4ay)

ch4a1y = ch4a1[0 + 1825 * b:1825 + 1825 * b]
ch4a1y = N.asarray(ch4a1y)
ch4a2y = ch4a2[0 + 1825 * b:1825 + 1825 * b]
ch4a2y = N.asarray(ch4a2y)

wta2y = wta2[0 + 1825 * b:1825 + 1825 * b]
wta2y = N.asarray(wta2y)

fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(311)

#xdates = [datetime.datetime.strptime(str(int(date)),'%Y') for date in xx]
#xdates = [datetime.date(2010, 1, 1), datetime.date(2015, 12, 27)]
months = MonthLocator(range(1, 13), bymonthday=1, interval=4)
monthsFmt = DateFormatter("%b '%y")

xdates = pd.date_range('2010-01-01', periods=1826, freq='D')
#print xdates
#xdates_new=pd.DatetimeIndex(data=(t for t in xdates if not isleap(t.year)), freq="D")
fig.autofmt_xdate()

leap = []
for each in xdates:
    if each.month == 2 and each.day == 29:
        leap.append(each)

xdates = xdates.drop(leap)
#print xdates
plt.ylim(-100, 800)
コード例 #4
0
    ax2.spines['right'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    
    # Hide the right and top spines
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)

    # Hide the right and top spines
    ax3.spines['right'].set_visible(False)
    ax3.spines['top'].set_visible(False)
    
    ax1.set_xlabel("")
    ax2.set_xlabel("")
    ax3.set_xlabel("")
    
    date_form = DateFormatter("%b\n%Y")
    ax1.xaxis.set_major_formatter(date_form)
    ax1.xaxis.set_major_locator(MonthLocator(interval=6))
    
    ax2.xaxis.set_major_formatter(date_form)
    ax2.xaxis.set_major_locator(MonthLocator(interval=6))
    
    ax3.xaxis.set_major_formatter(date_form)
    ax3.xaxis.set_major_locator(MonthLocator(interval=6))
    ax2.set_title(pixel)

    plt.minorticks_off()

    plt.show()
    
コード例 #5
0
"""
Show how to make date plots in matplotlib using date tick locators and
formatters.  See major_minor_demo1.py for more information on
controlling major and minor ticks
"""
import datetime
from pylab import figure, show
from matplotlib.dates import MONDAY, SATURDAY
from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter

date1 = datetime.date(2002, 1, 5)
date2 = datetime.date(2003, 12, 1)

mondays = WeekdayLocator(MONDAY)  # every monday
months = MonthLocator(range(1, 13), bymonthday=1)  # every month
monthsFmt = DateFormatter("%b '%y")

quotes = quotes_historical_yahoo('INTC', date1, date2)
if not quotes:
    print 'Found no quotes'
    raise SystemExit

dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]

fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(dates, opens, '-')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
コード例 #6
0
    def format_x_axis(self, ax, data_frame, gp, has_bar, bar_ind, has_matrix):

        if has_matrix:
            # ax.colorbar()
            # ax.xticks(rotation=90)
            ax.set_xticks(bar_ind)
            ax.set_xlim([0, len(bar_ind)])
            ax.set_yticks(bar_ind)
            ax.set_ylim([0, len(bar_ind)])
            ax.set_xticklabels(data_frame.columns, minor=False)
            ax.set_yticklabels(data_frame.index, minor=False)

            # ax.plot([], [])

            for y in range(len(data_frame.index)):
                for x in range(len(data_frame.columns)):
                    plt.text(
                        x + 0.5,
                        y + 0.5,
                        '%.0f' % data_frame.loc[y, x],
                        horizontalalignment='center',
                        verticalalignment='center',
                    )

            return

        if has_bar:
            ax.set_xticks(bar_ind)
            ax.set_xticklabels(data_frame.index)
            ax.set_xlim([-1, len(bar_ind)])

            # if lots of labels make text smaller and rotate
            if len(bar_ind) > 6:
                plt.setp(plt.xticks()[1], rotation=90)
                # plt.gca().tight_layout()
                # matplotlib.rcParams.update({'figure.autolayout': True})
                # plt.gcf().subplots_adjust(bottom=5)
                import matplotlib.dates as mdates

                if gp.date_formatter is not None:
                    ax.format_xdata = mdates.DateFormatter(gp.date_formatter)

                plt.tight_layout()
                # ax.tick_params(axis='x', labelsize=matplotlib.rcParams['font.size'] * 0.5)
            return

        # format X axis
        dates = data_frame.index

        # scaling for time series plots with hours and minutes only (and no dates)
        if hasattr(data_frame.index[0],
                   'hour') and not (hasattr(data_frame.index[0], 'month')):
            ax.xaxis.set_major_locator(MultipleLocator(86400. / 3.))
            ax.xaxis.set_minor_locator(MultipleLocator(86400. / 24.))
            ax.grid(b=True, which='minor', color='w', linewidth=0.5)

        # TODO have more refined way of formating time series x-axis!

        # scaling for time series plots with dates too
        else:
            # to handle dates
            try:
                dates = dates.to_pydatetime()
                diff = data_frame.index[-1] - data_frame.index[0]

                import matplotlib.dates as md

                if gp.date_formatter is not None:
                    ax.xaxis.set_major_formatter(
                        md.DateFormatter(gp.date_formatter))
                elif diff < timedelta(days=4):

                    # class MyFormatter(Formatter):
                    #     def __init__(self, dates, fmt='%H:%M'):
                    #         self.dates = dates
                    #         self.fmt = fmt
                    #
                    #     def __call__(self, x, pos=0):
                    #         'Return the label for time x at position pos'
                    #         ind = int(round(x))
                    #         if ind >= len(self.dates) or ind < 0: return ''
                    #
                    #         return self.dates[ind].strftime(self.fmt)
                    #
                    # formatter = MyFormatter(dates)
                    # ax.xaxis.set_major_formatter(formatter)

                    date_formatter = '%H:%M'
                    xfmt = md.DateFormatter(date_formatter)
                    ax.xaxis.set_major_formatter(xfmt)

                    if diff < timedelta(minutes=20):
                        ax.xaxis.set_major_locator(
                            MinuteLocator(byminute=range(60), interval=2))
                        ax.xaxis.set_minor_locator(MinuteLocator(interval=1))
                    elif diff < timedelta(hours=1):
                        ax.xaxis.set_major_locator(
                            MinuteLocator(byminute=range(60), interval=5))
                        ax.xaxis.set_minor_locator(MinuteLocator(interval=2))
                    elif diff < timedelta(hours=6):
                        locator = HourLocator(interval=1)
                        ax.xaxis.set_major_locator(locator)
                        ax.xaxis.set_minor_locator(MinuteLocator(interval=30))
                    elif diff < timedelta(days=3):
                        ax.xaxis.set_major_locator(HourLocator(interval=6))
                        ax.xaxis.set_minor_locator(HourLocator(interval=1))

                elif diff < timedelta(days=10):
                    locator = DayLocator(interval=2)
                    ax.xaxis.set_major_locator(locator)
                    ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %y'))

                    day_locator = DayLocator(interval=1)
                    ax.xaxis.set_minor_locator(day_locator)

                elif diff < timedelta(days=40):
                    locator = DayLocator(interval=10)
                    ax.xaxis.set_major_locator(locator)
                    ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %y'))

                    day_locator = DayLocator(interval=1)
                    ax.xaxis.set_minor_locator(day_locator)

                elif diff < timedelta(days=365 * 0.5):
                    locator = MonthLocator(bymonthday=1, interval=2)
                    ax.xaxis.set_major_locator(locator)
                    ax.xaxis.set_major_formatter(md.DateFormatter('%b %y'))

                    months_locator = MonthLocator(interval=1)
                    ax.xaxis.set_minor_locator(months_locator)

                elif diff < timedelta(days=365 * 2):
                    locator = MonthLocator(bymonthday=1, interval=3)
                    ax.xaxis.set_major_locator(locator)
                    ax.xaxis.set_major_formatter(md.DateFormatter('%b %y'))

                    months_locator = MonthLocator(interval=1)
                    ax.xaxis.set_minor_locator(months_locator)

                elif diff < timedelta(days=365 * 5):
                    locator = YearLocator()
                    ax.xaxis.set_major_locator(locator)
                    ax.xaxis.set_major_formatter(md.DateFormatter('%Y'))

            except:
                try:
                    # otherwise we have integers, rather than dates
                    # TODO needs smarter more generalised mapping of dates
                    max = dates.max()
                    min = dates.min()

                    big_step = self.round_to_1((max - min) / 10)

                    small_step = big_step / 5

                    ax.xaxis.set_major_locator(MultipleLocator(big_step))
                    ax.xaxis.set_minor_locator(MultipleLocator(small_step))

                    plt.xlim(min, max)
                except:
                    pass
コード例 #7
0
###########################################################
#Test behavior for missing values
#tairs[10]=-991. #Uncomment to test with artificial missing value
#tairs[20]=-991. #Uncomment to test with artificial missing value
#tairs[30:40]=[-991.]*10 #Uncomment to test with artificial missing value
###########################################################

###########################################################
#Use matplotlib to make a PNG file in the visit/ directory
figure(figsize=(12, 6))

#Define tick marks
years = YearLocator()  #Every year
yearsFmt = DateFormatter('%Y')
months = MonthLocator()  #Every month
monthsFmt = DateFormatter('%m')
days = DayLocator()  #Every day
daysFmt = DateFormatter('%d')
hours = HourLocator()  #Every hour
hoursFmt = DateFormatter('%H Z')
hours3 = HourLocator(range(0, 24, 3))  #Every 3 hours
hours6x = HourLocator(range(0, 24, 6))  #Every 6 hours

#Try these commands for testing:
#datesx=[x-dates[0] for x in dates]
#plot(datesx,dwpts,'k') #This uses the raw date in "days" on the x-axis
#plot_date(dates,tairs,'k') #This works nicely as long as you don't have missing values

y_maskedi = ma.MaskedArray(tairs)
y_masked = ma.masked_where(y_maskedi < -990.0,
コード例 #8
0
    def plot(self,
             timedata=None,
             udata=None,
             vdata=None,
             ylabel=None,
             **kwargs):

        if kwargs['rotate'] != 0.0:
            print "rotating vectors"
            angle_offset_rad = np.deg2rad(kwargs['rotate'])
            udata = udata * np.cos(angle_offset_rad) + vdata * np.sin(
                angle_offset_rad)
            vdata = -1 * udata * np.sin(angle_offset_rad) + vdata * np.cos(
                angle_offset_rad)

        magnitude = np.sqrt(udata**2 + vdata**2)

        fig = plt.figure(1)
        ax2 = plt.subplot2grid((2, 1), (0, 0), colspan=1, rowspan=1)
        ax1 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1)

        # Plot u and v components
        # Plot quiver
        ax1.set_ylim(-1 * np.nanmax(magnitude), np.nanmax(magnitude))
        fill1 = ax1.fill_between(timedata, magnitude, 0, color='k', alpha=0.1)

        # Fake 'box' to be able to insert a legend for 'Magnitude'
        p = ax1.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1))
        leg1 = ax1.legend([p], ["Current magnitude [cm/s]"], loc='lower right')
        leg1._drawFrame = False

        # 1D Quiver plot
        q = ax1.quiver(timedata,
                       0,
                       udata,
                       vdata,
                       color='r',
                       units='y',
                       scale_units='y',
                       scale=1,
                       headlength=1,
                       headaxislength=1,
                       width=0.04,
                       alpha=.95)
        qk = plt.quiverkey(q,
                           0.2,
                           0.05,
                           25,
                           r'$25 \frac{cm}{s}$',
                           labelpos='W',
                           fontproperties={'weight': 'bold'})

        # Plot u and v components
        ax1.set_xticklabels(ax1.get_xticklabels(), visible=True)
        ax2.set_xticklabels(ax2.get_xticklabels(), visible=True)
        ax1.axes.get_xaxis().set_visible(True)
        ax1.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5)
        ax1.set_ylabel("Velocity (cm/s)")
        ax2.plot(kwargs['timedata2'],
                 kwargs['data2'][:, 0, 0, 0],
                 'k-',
                 linewidth=1)
        ax2.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5)
        ax2.set_xlabel("Date (UTC)")
        ax2.set_ylabel("Salinity (PSU)")
        ax2.xaxis.set_major_locator(MonthLocator())
        ax2.xaxis.set_minor_locator(
            MonthLocator(bymonth=range(1, 13), bymonthday=15))
        ax2.xaxis.set_major_formatter(ticker.NullFormatter())
        ax2.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax1.xaxis.set_major_locator(MonthLocator())
        ax1.xaxis.set_minor_locator(
            MonthLocator(bymonth=range(1, 13), bymonthday=15))
        ax1.xaxis.set_major_formatter(ticker.NullFormatter())
        ax1.xaxis.set_minor_formatter(DateFormatter('%b %y'))
        ax2.spines['bottom'].set_visible(False)
        ax1.spines['top'].set_visible(False)
        ax1.xaxis.set_ticks_position('top')
        ax2.xaxis.set_ticks_position('bottom')
        ax2.yaxis.set_ticks_position('both')
        ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize)

        return plt, fig
コード例 #9
0
    def plot(self, xdata=None, ydata=None, **kwargs):
        """
      Purpose
      --------
      Plot all sfc met observations as one image
      """

        TC = ydata['AT_21'][:, 0, 0, 0]
        TD = ydata['RH_910'][:, 0, 0, 0]
        Press = ydata['BP_915'][:, 0, 0, 0]
        WindU = ydata['WU_422'][:, 0, 0, 0]
        WindV = ydata['WV_423'][:, 0, 0, 0]
        Rad = ydata['Qs_133'][:, 0, 0, 0]
        Teq = ydata['Teq_1800'][:, 0, 0, 0]
        bat = ydata['BAT_106'][:, 0, 0, 0]
        comp = ydata['comp_1404'][:, 0, 0, 0]

        fig = plt.figure()
        #text locations
        right = 0.05
        top = .95

        #TC, TD
        ax = fig.add_subplot(911)
        tplot = ax.plot(xdata, TC)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'r', 'linestyle', '-', 'linewidth', .5)
        ax.text(right,
                top,
                'Air Temperature ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('(Deg C)')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        #RH
        ax = fig.add_subplot(912)
        tplot = ax.plot(xdata, TD)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'g', 'linestyle', '-', 'linewidth', .5)
        ax.text(right,
                top,
                'Relative Humidity ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('%')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        #Press
        ax = fig.add_subplot(913)
        tplot = ax.plot(xdata, Press)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'k', 'linestyle', '-', 'linewidth', .5)
        ax.text(right,
                top,
                'Pressure ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('(mb)')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        # Plot quiver
        #WindU[WindU == np.nan] = 0
        #WindV[WindV == np.nan] = 0
        ax1 = fig.add_subplot(914)
        ax2 = fig.add_subplot(915)
        magnitude = (WindU**2 + WindV**2)**0.5
        ax1.set_ylim(-1 * np.nanmax(magnitude), np.nanmax(magnitude))
        ax1.set_xlim(min(xdata), max(xdata))

        fill1 = ax1.fill_between(xdata, magnitude, 0, color='k', alpha=0.1)

        # Fake 'box' to be able to insert a legend for 'Magnitude'
        p = ax1.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.5))
        leg1 = ax1.legend([p], ["Wind magnitude [m/s]"], loc='lower right')
        leg1._drawFrame = False

        # 1D Quiver plot
        q = ax1.quiver(xdata,
                       0,
                       WindU,
                       WindV,
                       color='r',
                       units='y',
                       scale_units='y',
                       scale=1,
                       headlength=1,
                       headaxislength=1,
                       width=0.04,
                       alpha=0.75)
        qk = plt.quiverkey(q,
                           0.2,
                           0.05,
                           2,
                           r'$2 \frac{m}{s}$',
                           labelpos='W',
                           fontproperties={'weight': 'bold'})

        # Plot u and v components
        ax1.set_ylabel("Velocity (m/s)")

        ax2.plot(xdata, WindV, 'b-')
        ax2.plot(xdata, WindU, 'g-')
        ax2.set_xlim(min(xdata), max(xdata))
        ax2.set_ylabel("Velocity (m/s)")
        ax2.yaxis.set_ticks_position('both')
        ax2.xaxis.set_major_locator(MonthLocator())
        ax2.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax2.xaxis.set_major_formatter(ticker.NullFormatter())
        ax2.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        ax2.tick_params(axis='x',
                        which='both',
                        bottom='off',
                        labelbottom='off')
        ax1.set_ylabel("Velocity (m/s)")
        ax1.yaxis.set_ticks_position('both')
        ax1.xaxis.set_major_locator(MonthLocator())
        ax1.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax1.xaxis.set_major_formatter(ticker.NullFormatter())
        ax1.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        ax1.tick_params(axis='x',
                        which='both',
                        bottom='off',
                        labelbottom='off')
        ax1.axes.get_xaxis().set_visible(False)
        ax1.spines['top'].set_visible(False)
        ax1.spines['bottom'].set_visible(False)
        ax2.axes.get_xaxis().set_visible(False)
        ax2.spines['top'].set_visible(False)
        ax2.spines['bottom'].set_visible(False)

        # Set legend location - See: http://matplotlib.org/users/legend_guide.html#legend-location
        leg2 = plt.legend(['v', 'u'], loc='upper left')
        leg2._drawFrame = False

        #Rad
        ax = fig.add_subplot(916)
        tplot = ax.plot(xdata, Rad)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'k', 'linestyle', '-', 'linewidth', .5)
        ax.fill_between(xdata, 0, Rad, facecolor='yellow')
        ax.text(right,
                top,
                'Shortwave Radiation  ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('(W*m^-2)')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        #system vars - equil temp, battery, compass
        ax = fig.add_subplot(917)
        tplot = ax.plot(xdata, Teq)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'k', 'linestyle', '-', 'linewidth', .5)
        ax.text(right,
                top,
                'Teq ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        ax = fig.add_subplot(918)
        tplot = ax.plot(xdata, bat)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'k', 'linestyle', '-', 'linewidth', .5)
        ax.text(right,
                top,
                'battery ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('volts')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(axis='x', which='both', bottom='off', labelbottom='off')
        ax.spines['bottom'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('both')

        ax = fig.add_subplot(919)
        tplot = ax.plot(xdata, comp)
        ax.set_xlim(min(xdata), max(xdata))
        plt.setp(tplot, 'color', 'k', 'linestyle', 'None', 'marker', '.',
                 'markersize', 2.5)
        ax.text(right,
                top,
                'compass ',
                horizontalalignment='left',
                verticalalignment='top',
                transform=ax.transAxes)
        plt.ylabel('degrees')
        ax.xaxis.set_major_locator(MonthLocator())
        ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_formatter(DateFormatter('%b %y'))
        ax.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        ax.tick_params(axis='y', which='major', labelsize=self.labelsize)
        ax.tick_params(axis='x', which='both', top='off')
        ax.spines['top'].set_visible(False)
        ax.set_xlabel("Date (UTC)")

        return (plt, fig)
コード例 #10
0
    def plot(self,transactions=None):
        """Plot balance v. time"""
        self.figure.clf()
        if transactions is None:
            transactions=self.transactions
        #ax=pyfin.linePlot(transactions)
        ax=self.figure.add_subplot(111)
        #self.figure.axes.append(ax)

        lineplot=[]
        for q in transactions:
            lineplot.append([q.date,-q.amt,q.descr,q.cat])
        #print('\n'.join(['%s\t%.2f\t%s\t%s'%(q[0],q[1],q[2],q[3][0]) for q in lineplot]))
        lineplot=[list(q) for q in zip(*lineplot[::])]
        lsum=[0]
        #print(len(lineplot))
        for i in range(len(lineplot[1])):
            lsum.append(lsum[-1]+lineplot[1][i])   # Array of running balance
        lsum=lsum[1:]                              # Delete [0] entry
        #print('***'*10,lsum[-1]);sys.exit()

        #xdata=[q.toordinal() for q in lineplot[0]] # Dates
        # Fill array with dates every day since oldest
        dates=[lineplot[0][0]]
        #print(dates)
        while dates[-1]<datetime.date.today():
            dates.append(dates[-1]+datetime.timedelta(days=1))

        currbal=[0]                                # Get current balance
        for date in dates:
            adding=0
            for i in range(len(lineplot[0])):
                if date==lineplot[0][i]:
                    adding+=lineplot[1][i]         # Add all current date transactions to balance
            currbal.append(currbal[-1]+adding)     # Keep daily array of running balance
        currbal=currbal[1:]                        # Delete [0] element

        ndayrunningavg=21                          # Smoothing function
        ndaypad=int((ndayrunningavg-1)/2)
        tda=currbal[:ndaypad]                      # Fill first 20 days without smoothing, then smooth rest
        for i in range(ndaypad,len(currbal)-ndaypad):
            tda.append(sum(currbal[i-ndaypad:i+ndaypad+1])/float(ndayrunningavg))
        for s in currbal[-ndaypad:]:               # Append last 20 days without smoothing
            tda.append(s)

        sundays=WeekdayLocator(SUNDAY)
        months=MonthLocator(range(1,13),bymonthday=1,interval=1)
        monthsFmt=DateFormatter('%b %y')

        #fig,ax=plt.subplots()
        ax.plot_date(lineplot[0],lsum,'ko')
        #print(len(dates),len(tda))
        ax.plot_date(dates,tda,'c--')
        ax.plot_date(dates,currbal,'r-')

        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_major_formatter(monthsFmt)
        ax.xaxis.set_minor_locator(sundays)
        ax.autoscale_view()
        ax.grid(True)
        self.figure.autofmt_xdate()
        #plt.show()

        self.draw()
        return
コード例 #11
0
    def plot(self,
             timedata=None,
             udata=None,
             vdata=None,
             ylabel=None,
             **kwargs):

        if kwargs['rotate'] != 0.0:
            #when rotating vectors - positive(+) rotation is equal to cw of the axis (ccw of vector)
            #                      - negative(+) rotation is equal to ccw of the axis (cw of the vector)
            print "rotating vectors"
            angle_offset_rad = np.deg2rad(kwargs['rotate'])
            udata = udata * np.cos(angle_offset_rad) + vdata * np.sin(
                angle_offset_rad)
            vdata = -1. * udata * np.sin(angle_offset_rad) + vdata * np.cos(
                angle_offset_rad)

        magnitude = np.sqrt(udata**2 + vdata**2)

        fig = plt.figure(1)
        ax1 = plt.subplot2grid((2, 1), (0, 0), colspan=1, rowspan=1)
        ax2 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1)

        # Plot u and v components
        # Plot quiver
        ax1.set_ylim(-1 * np.nanmax(magnitude), np.nanmax(magnitude))
        fill1 = ax1.fill_between(timedata, magnitude, 0, color='k', alpha=0.1)

        # Fake 'box' to be able to insert a legend for 'Magnitude'
        p = ax1.add_patch(plt.Rectangle((1, 1), 1, 1, fc='k', alpha=0.1))
        leg1 = ax1.legend([p], ["Current magnitude [cm/s]"], loc='lower right')
        leg1._drawFrame = False

        # 1D Quiver plot
        q = ax1.quiver(timedata,
                       0,
                       udata,
                       vdata,
                       color='r',
                       units='y',
                       scale_units='y',
                       scale=1,
                       headlength=1,
                       headaxislength=1,
                       width=0.04,
                       alpha=.95)
        qk = plt.quiverkey(q,
                           0.2,
                           0.05,
                           5,
                           r'$5 \frac{cm}{s}$',
                           labelpos='W',
                           fontproperties={'weight': 'bold'})

        # Plot u and v components
        ax1.set_xticklabels(ax1.get_xticklabels(), visible=False)
        ax2.set_xticklabels(ax2.get_xticklabels(), visible=True)
        ax1.axes.get_xaxis().set_visible(False)
        ax1.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5)
        ax1.set_ylabel("Velocity (cm/s)")
        ax2.plot(timedata, vdata, 'b-', linewidth=0.25)
        ax2.plot(timedata, udata, 'g-', linewidth=0.25)
        ax2.set_xlim(timedata.min() - 0.5, timedata.max() + 0.5)
        ax2.set_xlabel("Date (UTC)")
        ax2.set_ylabel("Velocity (cm/s)")
        ax2.xaxis.set_major_locator(MonthLocator())
        ax2.xaxis.set_minor_locator(
            MonthLocator(bymonth=range(1, 13), bymonthday=15))
        ax2.xaxis.set_major_formatter(ticker.NullFormatter())
        ax2.xaxis.set_minor_formatter(DateFormatter('%b %y'))
        ax1.spines['bottom'].set_visible(False)
        ax2.spines['top'].set_visible(False)
        ax1.xaxis.set_ticks_position('top')
        ax2.xaxis.set_ticks_position('bottom')
        ax2.yaxis.set_ticks_position('both')
        ax2.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        ax1.tick_params(axis='both', which='minor', labelsize=self.labelsize)
        #manual time limit sets
        #ax1.set_xlim([datetime.datetime(2016,2,1),datetime.datetime(2016,9,15)])
        #ax2.set_xlim([datetime.datetime(2016,2,1),datetime.datetime(2016,9,15)])
        # Set legend location - See: http://matplotlib.org/Volumes/WDC_internal/users/legend_guide.html#legend-location
        leg2 = plt.legend(['v', 'u'], loc='upper left')
        leg2._drawFrame = False

        return plt, fig
コード例 #12
0
 def __init__(self):
     start=365*1+1
     self.dates=[date.fromordinal(i) for i in range(start,start+365)]
     self.monthsFmt = DateFormatter("%b")
     self.months = MonthLocator(range(1, 13), bymonthday=1, interval=3)
コード例 #13
0
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, YearLocator
import numpy as np

fig, ax = plt.subplots(1, 1)

x = np.arange('1965-01', '1975-07', dtype='datetime64[D]')
y = np.random.randn(x.size).cumsum()
ax.plot(x, y)

yloc = YearLocator()
mloc = MonthLocator()
ax.xaxis.set_major_locator(yloc)
ax.xaxis.set_minor_locator(mloc)
ax.grid(True)
コード例 #14
0
ファイル: covid_bln.py プロジェクト: fdietel/analyzing-covid
# In[6]:

fig, ax = plt.subplots(figsize=(16, 9), dpi=150)

ax.bar(covid_bln.index,
       covid_bln['neue_faelle'],
       color='lightsteelblue',
       label="per day",
       alpha=0.7,
       width=1)
ax.set_ylabel("new cases", fontsize=15)

ax.plot(covid_bln.index, covid_bln['7_tage_mittel'], label='7-day mean')

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.xaxis.set_major_locator(MonthLocator())

ax.set_title("", fontsize=15)
ax.set_ylabel("new cases", fontsize=15)
ax.legend()

plt.style.use('seaborn')
plt.tight_layout()
plt.show()

# The maximum of 1,960 new registered cases was reached on November 12, 2020. The 7-day mean peaked on November 18, 2020 with 1,273.9 cases.

# ### 7-day incidence rate

# In[7]:
コード例 #15
0
ファイル: grappher.py プロジェクト: taoprajjwal/NBAGrapher
def plot_team_game(teams,
                   stat,
                   season,
                   start_date,
                   end_date,
                   opp=False,
                   xlabel="Time",
                   ylabel=None,
                   only_month=False,
                   scatter=True,
                   return_type="img",
                   cum=False):
    """
    Uses Sportsreference

    :param teams: Basketball-reference id for team
    :type teams: String or list of strings
    :param stat: The statistical attribute of the player to plot
    :type stat: String
    :param season: The season in which the games are played
    :type season: Either in dashed form (2018-19) or single form (2019 means the season 2018-19)
    :param start_date: The date from which the data is plotted
    :type start_date: datetime.date format
    :param end_date: The date untill which data is plotted
    :type end_date: datetime.date format
    :param opp: Whether the stat is for the opponent
    :type opp: Bool
    :param xlabel: The label on the x-axis on the returned plot
    :type xlabel: String
    :param ylabel: The label on the Y-axis on the returned plot
    :type ylabel: String
    :param scatter: Whether on not to include a dot for each data point in the graph
    :type scatter: Bool
    :param return_type: Various methods by which the graph can be returned
    :type return_type: "img": png image, "fig":Matplotlib figure and axes,"show": calls the matplotlib show function (appropriate for jupyter notebooks), "html": base64 image useful for rendering in html pages
    :param cum: Whether results are cumulative or not
    :type cum: Bool
    """
    fig, ax = plt.subplots()
    if type(teams) is not list:
        teams = [teams]
    for team in teams:
        x = []
        y = []
        sch = Schedule(team, season)
        for index, row in sch.dataframe.iterrows():
            if start_date <= row['datetime'].date() <= end_date:
                box = Boxscore(index)
                stat_prefix = ""
                stat_prefix_reversal = {"home_": "away_", "away_": "home_"}

                if row['location'] == "Home":
                    stat_prefix = "home_"
                elif row['location'] == "Away":
                    stat_prefix = "away_"

                if opp:
                    stat_prefix = stat_prefix_reversal[stat_prefix]

                x.append(row['datetime'].date())
                if cum:
                    try:
                        prev = y[-1]
                    except:
                        prev = 0

                    y.append(int(box.dataframe[stat_prefix + stat]) + prev)

                else:
                    y.append(int(box.dataframe[stat_prefix + stat]))

        ax.plot(x, y, label=team)
        if scatter:
            ax.scatter(x, y)
        ax.legend()
        if only_month:
            ax.xaxis.set_major_locator(MonthLocator())
            ax.xaxis.set_major_formatter(DateFormatter("%y-%m"))

    fig.autofmt_xdate()
    ax.set_xlabel(xlabel)
    if ylabel == None:
        if opp:
            ax.set_ylabel("opp_" + stat)
        else:
            ax.set_ylabel(stat)

    return return_plot(stat, fig, ax, return_type)
コード例 #16
0
def plot_docs_visits(analyics_csvfn, **plotkws):
    """
    Requires a CSV file downloaded from the astropy google analytics page.
    Should have at least the "all sessions" and "Docs visits" segments exported
    from Apr 1 2012 (~when data taking started) to now.
    """
    from datetime import datetime
    from astropy.table import Table
    from astropy.time import Time
    from matplotlib.dates import YearLocator, MonthLocator, DateFormatter

    #first read the data
    tab = Table.read(analyics_csvfn,
                     format='csv',
                     data_start=6,
                     header_start=5)

    # now extract the data

    if tab.colnames[0] == 'Day Index':
        #it's just days, so parse them as such
        times = []
        time_msk = []
        for day, masked in zip(tab['Day Index'], tab['Day Index'].mask):
            if masked:
                times.append(datetime(2000, 1, 1))  #prior to astropy
                time_msk.append(False)
            else:
                times.append(datetime.strptime(day, '%m/%d/%y'))
                time_msk.append(True)

        times = Time(times)
        # remove the final day because it might be incomplete
        time_msk = np.array(time_msk) & (times != np.max(times))

    else:  # it's something more complex with an inex and a range
        index = tab[tab.colnames[
            0]]  # might be called "week index" or "day index" or whatever

        date_range = tab['Date Range'][0]
        if not np.all(date_range == tab['Date Range']):
            raise ValueError(
                'Do not know how to deal with multiple date ranges...')

        t1, t2 = [
            Time(datetime.strptime(dr, '%b %d, %Y'))
            for dr in date_range.split(' - ')
        ]
        dti = (t2 - t1) / np.max(index)
        times = t1 + index.view(np.ndarray) * dti

        # remove the final index because it might be incomplete
        time_msk = (index != np.max(index)) & ~index.mask

    all_msk = (tab['Segment'] == 'All Sessions') & time_msk
    docs_msk = (tab['Segment'] == 'Docs Visits') & time_msk

    n_docs = [
        float(numstr.replace(',', '')) for numstr in tab['Sessions'][docs_msk]
    ]
    times_docs = times[docs_msk]
    n_all = [
        float(numstr.replace(',', '')) for numstr in tab['Sessions'][all_msk]
    ]
    times_all = times[all_msk]

    #now plot
    fig = plt.gcf()
    ax = plt.gca()

    plotkws.setdefault('lw', 2)
    plotkws.setdefault('ls', '-')
    plotkws.setdefault('ms', 0)
    ax.plot_date(times_docs.plot_date, n_docs, **plotkws)

    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(MonthLocator())
    ax.autoscale_view()

    fig.autofmt_xdate()

    plt.ylabel('Docs Visits', fontsize=30)
    plt.xticks(fontsize=20)
    plt.tight_layout()

    return (times_docs, n_docs), (times_all, n_all)
コード例 #17
0
    def PlotClySet(self):
        #----------------------------------------
        #Define global interes
        #----------------------------------------
        loi = 45  #Ltitude of interest
        poi = 10.  #Ppressure of interest
        y4trend = 1997  #initial year if trends

        #----------------------------------------
        #           GOZCARDS (MERGE OF HALOE, ACE, MLS)
        #----------------------------------------

        if self.ReadNCMrgFlg:

            time = np.asarray(self.Mrg['time'])
            Prfs = np.asarray(self.Mrg['average']) * 1e9
            lev = np.asarray(self.Mrg['lev'])
            Latitude = np.asarray(self.Mrg['lat'])
            std_dev = np.asarray(self.Mrg['std_dev']) * 1e9

            Nfiles = time.shape[0]
            NMonths = time.shape[1]
            Nlat = Latitude.shape[1]
            Nlev = lev.shape[1]

            print '\nN GOZCARDS files = ', Nfiles
            print 'N GOZCARDS Months = ', NMonths
            print 'N GOZCARDS Latitudes = ', Nlat
            print 'N GOZCARDS Levels = ', Nlev

            Dates = np.asarray(
                [[dt.date(1950, 1, 1) + dt.timedelta(days=int(t)) for t in tt]
                 for tt in time])

            DatesMrg = np.reshape(Dates, (Nfiles * NMonths))
            PrfsMrg = np.reshape(Prfs, (Nfiles * NMonths, Nlev, Nlat))
            PresMrg = lev[0, :]
            LatMrg = Latitude[0, :]
            StDMrg = np.reshape(std_dev, (Nfiles * NMonths, Nlev, Nlat))

            #----------------------------------------
            #DELETE POINTS IN THE pressure and latitude of interest (Important because some values are negatives)
            #----------------------------------------
            indMrg1 = mf.nearestind(poi, PresMrg)
            indLatMrg = mf.nearestind(loi, LatMrg)
            indsBad = np.where(PrfsMrg[:, indMrg1, indLatMrg] < 0.0)[0]

            print 'N points to remove in GOZCARDS = {}'.format(len(indsBad))
            PrfsMrg = np.delete(PrfsMrg, indsBad, axis=0)
            StDMrg = np.delete(StDMrg, indsBad, axis=0)
            DatesMrg = np.delete(DatesMrg, indsBad, axis=0)

            #----------------------------------------
            #           Read AGAGE
            #----------------------------------------

        if self.ReadAgaFlg:
            #----------------------------------------
            #DEFINE VARIABLES
            #----------------------------------------
            Nsites = len(self.AGA['site'])
            s = self.AGA['site']
            Lat = np.asarray(self.AGA['lat'])

            indLatAGA = mf.nearestind(53., Lat)  ## This is to read MACE, HEAD
            ##indLatAGA = mf.nearestind(loi, Lat)  ## This is to read Closest to loi

            print '\nAGAGE site for Plot: {}, --> Latitude: {}'.format(
                self.AGA['site'][indLatAGA], Lat[indLatAGA])

            DatesAGA = np.asarray(self.AGA[s[indLatAGA] + 'Dates'][0])

            if self.AgagefileID == 0:

                CFC11 = np.asarray(self.AGA[s[indLatAGA] + 'CFC11'][0])
                CFC11_e = np.asarray(self.AGA[s[indLatAGA] + 'CFC11_e'][0])

                CFC12 = np.asarray(self.AGA[s[indLatAGA] + 'CFC12'][0])
                CFC12_e = np.asarray(self.AGA[s[indLatAGA] + 'CFC12_e'][0])

                CCl4 = np.asarray(self.AGA[s[indLatAGA] + 'CCl4'][0])
                CCl4_e = np.asarray(self.AGA[s[indLatAGA] + 'CCl4_e'][0])

                CFC113 = np.asarray(self.AGA[s[indLatAGA] + 'CFC113'][0])
                CFC113_e = np.asarray(self.AGA[s[indLatAGA] + 'CFC113_e'][0])

                ind = np.where((CFC11 > 0.) & (CFC12 > 0.) & (CCl4 > 0.))[0]

                Cl = CFC11[ind] + CFC12[ind] + CCl4[ind]
                Cl_e = np.sqrt(CFC11_e[ind]**2 + CFC12_e[ind]**2 +
                               CCl4_e[ind]**2)
                DatesAGA = DatesAGA[ind]

            elif self.AgagefileID == 1:

                Cl = np.asarray(self.AGA[s[indLatAGA] + 'Cly'][0])

                #----------------------------------------
                #           Read JFJ
                #----------------------------------------

        f = open(self.jfjFile, 'r')

        HCl_Date_JFJ = []
        HCl_JFJ = []
        CLONO2_Date_JFJ = []
        CLONO2_JFJ = []

        Cl_Date_JFJ = []
        Cl_JFJ = []

        header1 = f.readline()

        for line in f:
            columns = line.split()
            atime = float(columns[0])

            da_i = mf.t2dt(atime)
            if da_i.year >= 1983:
                HCl_Date_JFJ.append(da_i)
                HCl_JFJ.append(float(columns[1]) / 1e15)

            if len(columns) >= 3:

                atime = float(columns[2])
                da_i = mf.t2dt(atime)
                if da_i.year >= 1983:
                    CLONO2_Date_JFJ.append(da_i)
                    CLONO2_JFJ.append(float(columns[3]) / 1e15)

            if len(columns) >= 5:
                atime = float(columns[4])
                da_i = mf.t2dt(atime)
                if da_i.year >= 1983:
                    Cl_Date_JFJ.append(da_i)
                    Cl_JFJ.append(float(columns[5]) / 1e15)

        HCl_Date_JFJ = np.asarray(HCl_Date_JFJ)
        HCl_JFJ = np.asarray(HCl_JFJ)

        Cl_JFJ = np.asarray(Cl_JFJ)
        Cl_Date_JFJ = np.asarray(Cl_Date_JFJ)

        #----------------------------------------
        #           Read MLO
        #----------------------------------------

        f = open(self.mloFile, 'r')

        HCl_Date_MLO = []
        HCl_MLO = []

        headers = [f.readline() for i in range(7)]

        for line in f:

            columns = line.split(',')

            yyyy = int(columns[1].strip()[0:4])
            mm = int(columns[1].strip()[5:7])
            dd = int(columns[1].strip()[8:10])

            hh = int(columns[2].strip()[0:2])
            mi = int(columns[2].strip()[3:5])
            se = int(columns[2].strip()[6:8])

            da = dt.datetime(yyyy, mm, dd, hh, mi, se)

            HCl_Date_MLO.append(da)
            HCl_MLO.append(float(columns[3].strip()))

        HCl_MLO = np.asarray(HCl_MLO) / 1e15
        HCl_Date_MLO = np.asarray(HCl_Date_MLO)

        Avg = mf.mnthlyAvg(HCl_MLO, HCl_Date_MLO, dateAxis=1)
        HCl_Date_MLO = Avg['dates']
        HCl_MLO = Avg['mnthlyAvg']
        HCl_std_MLO = Avg['std']

        #----------------------------------------------------------------------------
        #
        #----------------------------------------------------------------------------
        years = [singDate.year
                 for singDate in DatesMrg]  # Find years for all date entries
        if len(list(set(years))) > 1:
            yrsFlg = True  # Determine all unique years
        else:
            yrsFlg = False

        yearsLc = YearLocator(2)
        monthsAll = MonthLocator()
        #months       = MonthLocator()
        months = MonthLocator(bymonth=1, bymonthday=1)
        if yrsFlg: DateFmt = DateFormatter('%Y')
        else: DateFmt = DateFormatter('%m\n%Y')

        #----------------------------------------------------------------------------
        #
        #----------------------------------------------------------------------------
        indLatMrg = mf.nearestind(loi, LatMrg)

        #-----------------------------------------
        #             PLOT (ONE PANEL, THREE Y-AXIS)
        #-----------------------------------------
        fig, ax = plt.subplots(figsize=(12, 7), sharex=True)

        axes = [ax, ax.twinx(), ax.twinx()]

        axes[-1].spines['right'].set_position(('axes', 1.125))
        axes[-1].set_frame_on(True)
        axes[-1].patch.set_visible(False)

        #-----------------------------------------
        #PLOT GOZCARDS
        #-----------------------------------------
        if self.ReadHDFMLSFlg: ind1MLS = mf.nearestind(poi, PresMLS)
        if self.ReadNCMrgFlg: indMrg1 = mf.nearestind(poi, PresMrg)

        indsGood = np.where(PrfsMrg[:, indMrg1, indLatMrg] > 0.0)[0]

        PrfsMrg2 = PrfsMrg[indsGood, indMrg1, indLatMrg]
        StDMrg2 = StDMrg[indsGood, indMrg1, indLatMrg]
        DatesMrg2 = DatesMrg[indsGood]

        PrfsMrg2_smth = mf.smooth(PrfsMrg2, window_len=24, window='flat')
        axes[0].plot(DatesMrg2, PrfsMrg2_smth, linewidth=5, color='gray')

        #-----------------------------------------
        #GOZCARDS TRENDS ANALYSIS
        #-----------------------------------------
        yearGO = [single.year for single in DatesMrg2]
        yearGO = np.asarray(yearGO)

        inds = np.where(yearGO >= y4trend)[0]

        dateYearFrac = mf.toYearFraction(DatesMrg2[inds])
        weights = np.ones_like(dateYearFrac)
        res = mf.fit_driftfourier(dateYearFrac, PrfsMrg2[inds], weights, 2)
        f_drift, f_fourier, f_driftfourier = res[3:6]

        res_b = mf.cf_driftfourier(dateYearFrac, PrfsMrg2[inds], weights, 2)
        perc, intercept_b, slope_b, pfourier_b = res_b

        print "\nFitted trend GOZCARDS -- slope: {0:.3E} ({1:.3f}%)".format(
            res[1], res[1] / np.nanmean(PrfsMrg2[inds]) * 100.0)
        axes[0].scatter(
            DatesMrg2,
            PrfsMrg2,
            s=20,
            color='gray',
            edgecolors='gray',
            alpha=0.75,
            label=
            'GOZCARDS (10hPa, 40-50$^\circ$ N)\n {0:.2f} $\pm$ {1:.2f} %/yr'.
            format(res[1] / np.nanmean(PrfsMrg2[inds]) * 100.0,
                   np.std(slope_b) / np.mean(PrfsMrg2[inds]) *
                   100.0))  #facecolors='none'
        axes[0].tick_params(which='both', labelsize=14)
        axes[0].set_ylim(1.7, 3.4)
        axes[0].set_ylabel('VMR [ppb], GOZCARDS (HALOE, ACE & MLS) (HCl)',
                           fontsize=14)

        if yrsFlg:
            axes[0].xaxis.set_major_locator(yearsLc)
            axes[0].xaxis.set_minor_locator(months)
            axes[0].xaxis.set_major_formatter(DateFmt)

        else:
            axes[0].xaxis.set_major_locator(monthsAll)
            axes[0].xaxis.set_major_formatter(DateFmt)

        # #-----------------------------------------
        # #SAVE GOZCARDS DATA IN ASCII
        # #-----------------------------------------
        # YYYYMMDD = np.asarray(['{0:4d}-{1:02d}-{2:02d}'.format(DatesMrg2[i].year, DatesMrg2[i].month, DatesMrg2[i].day)    for i,dum in enumerate(DatesMrg2)])

        # with open('/data1/Campaign/Satellite/MLS/GOZCARD_pltCly.ascii','w') as fopen:
        #     fopen.write('#Hannigan, J.W., Ortega, I\n')
        #     fopen.write('#National Center for Atmospheric Research\n')
        #     fopen.write('#GOZCARDS Monthly data (GOZCARDS (10hPa, 40-50deg N)\n')
        #     fopen.write('#GOZCARDS smoothed data is included using a window of 24 (2 years)\n')
        #     fopen.write('#CONTACT_INFO: Hannigan, Jim, [email protected], 303-497-1853, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')
        #     fopen.write('#CONTACT_INFO: Ortega, Ivan, [email protected], 303-497-1861, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')

        #     fopen.write('Index, YYYY-MM-DD, HCl [ppb], HCl_smooth [ppb]\n')
        #     strFormat = '{0:d}, {1:>10s},  {2:.3f}, {3:.3f}\n'

        #     for i,sngTime in enumerate(YYYYMMDD):
        #         fopen.write(strFormat.format((i+1),YYYYMMDD[i], PrfsMrg2[i], PrfsMrg2_smth[i]))

        #-----------------------------------------
        #PLOT AGAGE
        #-----------------------------------------
        if self.AgagefileID == 0:
            axes[1].set_ylabel('VMR [ppt], AGAGE (CFC11 + CFC12 + CCl$_4$)',
                               color='green',
                               fontsize=14)
        if self.AgagefileID == 1:
            axes[1].set_ylabel('Mole Fraction [ppb], AGAGE (Total Cl)',
                               color='green',
                               fontsize=14)
        axes[1].tick_params(axis='y', colors='green', labelsize=14)
        if self.AgagefileID == 0: axes[1].set_ylim(380, 1100)
        if self.AgagefileID == 1: axes[1].set_ylim(1, 4.5)

        yearAGA = [single.year for single in DatesAGA]
        yearAGA = np.asarray(yearAGA)

        #-----------------------------------------
        #AGAGE TRENDS ANALYSIS
        #-----------------------------------------
        inds = np.where(yearAGA >= y4trend)[0]

        dateYearFrac = mf.toYearFraction(DatesAGA[inds])
        weights = np.ones_like(dateYearFrac)
        res = mf.fit_driftfourier(dateYearFrac, Cl[inds], weights, 2)
        f_drift, f_fourier, f_driftfourier = res[3:6]

        res_b = mf.cf_driftfourier(dateYearFrac, Cl[inds], weights, 2)
        perc, intercept_b, slope_b, pfourier_b = res_b

        print "Fitted trend AGAGE -- slope: {0:.3E} ({1:.3f}%)".format(
            res[1], res[1] / np.mean(Cl[inds]) * 100.0)
        if self.AgagefileID == 0:
            axes[1].scatter(
                DatesAGA,
                Cl,
                s=20,
                color='green',
                edgecolors='green',
                alpha=0.75,
                label=
                'AGAGE Mace Head, Ireland (53.33$^\circ$ N)\n {0:.2f} $\pm$ {1:.2f} %/yr'
                .format(res[1] / np.nanmean(Cl[inds]) * 100.0,
                        np.std(slope_b) / np.mean(Cl[inds]) *
                        100.0))  #facecolors='none'
        if self.AgagefileID == 1:
            axes[1].scatter(
                DatesAGA,
                Cl,
                s=20,
                color='green',
                edgecolors='green',
                alpha=0.75,
                label=
                'AGAGE Global Mean Tropospheric Total Cl\n {0:.2f} $\pm$ {1:.2f} %/yr'
                .format(res[1] / np.nanmean(Cl[inds]) * 100.0,
                        np.std(slope_b) / np.mean(Cl[inds]) *
                        100.0))  #facecolors='none'

        # #-----------------------------------------
        # #SAVE AGAGE DATA IN ASCII
        # #-----------------------------------------
        #  YYYYMMDD = np.asarray(['{0:4d}-{1:02d}-{2:02d}'.format(DatesAGA[i].year, DatesAGA[i].month, DatesAGA[i].day)    for i,dum in enumerate(DatesAGA)])

        #  with open('/data1/Campaign/Satellite/MLS/AGAGE_pltCly.ascii','w') as fopen:
        #      fopen.write('#Hannigan, J.W., Ortega, I\n')
        #      fopen.write('#National Center for Atmospheric Research\n')
        #      fopen.write('#AGAGE  Monthly data from Mace Head, Ireland (53.33deg N)\n')
        #      fopen.write('#AGAGE  Cly =  CFC11 + CFC12 + CCl4\n')
        #      fopen.write('#CONTACT_INFO: Hannigan, Jim, [email protected], 303-497-1853, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')
        #      fopen.write('#CONTACT_INFO: Ortega, Ivan, [email protected], 303-497-1861, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')

        #      fopen.write('Index, YYYY-MM-DD, Cly [ppm]\n')
        #      strFormat = '{0:d}, {1:>10s},  {2:.3f}\n'

        #      for i,sngTime in enumerate(YYYYMMDD):
        #          fopen.write(strFormat.format((i+1),YYYYMMDD[i], Cl[i]))

        #-----------------------------------------
        #PLT JFJ HRFTIR
        #-----------------------------------------

        HCl_JFJ_smth = mf.smooth(HCl_JFJ, window_len=24, window='flat')
        axes[2].plot(HCl_Date_JFJ, HCl_JFJ_smth, linewidth=5, color='blue')

        yearJFJ = [single.year for single in HCl_Date_JFJ]
        yearJFJ = np.asarray(yearJFJ)

        inds = np.where(yearJFJ >= y4trend)[0]

        dateYearFrac = mf.toYearFraction(HCl_Date_JFJ[inds])
        weights = np.ones_like(dateYearFrac)
        res = mf.fit_driftfourier(dateYearFrac, HCl_JFJ[inds], weights, 2)
        f_drift, f_fourier, f_driftfourier = res[3:6]

        res_b = mf.cf_driftfourier(dateYearFrac, HCl_JFJ[inds], weights, 2)
        perc, intercept_b, slope_b, pfourier_b = res_b

        print "Fitted trend JFJ -- slope: {0:.3E} ({1:.3f}%)".format(
            res[1], res[1] / np.mean(HCl_JFJ[inds]) * 100.0)
        axes[2].scatter(
            HCl_Date_JFJ,
            HCl_JFJ,
            s=20,
            color='blue',
            edgecolors='blue',
            alpha=0.75,
            label=
            'Jungfraujoch NDACC FTIR (46.55$^\circ$ N)\n {0:.2f} $\pm$ {1:.2f} %/yr'
            .format(res[1] / np.nanmean(HCl_JFJ[inds]) * 100.0,
                    np.std(slope_b) / np.mean(HCl_JFJ[inds]) * 100.0))

        # #-----------------------------------------
        # #SAVE JFJ DATA IN ASCII
        # #-----------------------------------------
        # YYYYMMDD = np.asarray(['{0:4d}-{1:02d}-{2:02d}'.format(HCl_Date_JFJ[i].year, HCl_Date_JFJ[i].month, HCl_Date_JFJ[i].day)    for i,dum in enumerate(HCl_Date_JFJ)])

        # with open('/data1/Campaign/Satellite/MLS/JFJ_pltCly.ascii','w') as fopen:
        #     fopen.write('#Hannigan, J.W., Ortega, I\n')
        #     fopen.write('#National Center for Atmospheric Research\n')
        #     fopen.write('#Jungfraujoch NDACC FTIR Monthly Data (46.55deg N)\n')
        #     fopen.write('#Jungfraujoch smoothed data is included using a window of 24 (2 years)\n')
        #     fopen.write('#CONTACT_INFO: Hannigan, Jim, [email protected], 303-497-1853, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')
        #     fopen.write('#CONTACT_INFO: Ortega, Ivan, [email protected], 303-497-1861, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')

        #     fopen.write('Index, YYYY-MM-DD, HCl [[x10^15 molec/cm^2]], HCl_smooth [[x10$^15 molec/cm^2]]\n')
        #     strFormat = '{0:d}, {1:>10s},  {2:.3f}, {3:.3f}\n'

        #     for i,sngTime in enumerate(YYYYMMDD):
        #         fopen.write(strFormat.format((i+1),YYYYMMDD[i], HCl_JFJ[i], HCl_JFJ_smth[i]))

        #-----------------------------------------
        #PLT MLO HRFTIR
        #-----------------------------------------

        HCl_MLO_smth = mf.smooth(HCl_MLO, window_len=24, window='flat')
        axes[2].plot(HCl_Date_MLO, HCl_MLO_smth, linewidth=5, color='navy')

        yearMLO = [single.year for single in HCl_Date_MLO]
        yearMLO = np.asarray(yearMLO)

        inds = np.where(yearMLO >= y4trend)[0]

        dateYearFrac = mf.toYearFraction(HCl_Date_MLO[inds])
        weights = np.ones_like(dateYearFrac)
        res = mf.fit_driftfourier(dateYearFrac, HCl_MLO[inds], weights, 2)
        f_drift, f_fourier, f_driftfourier = res[3:6]

        res_b = mf.cf_driftfourier(dateYearFrac, HCl_JFJ[inds], weights, 2)
        perc, intercept_b, slope_b, pfourier_b = res_b

        print "Fitted trend MLO -- slope: {0:.3E} ({1:.3f}%)".format(
            res[1], res[1] / np.mean(HCl_MLO[inds]) * 100.0)

        axes[2].scatter(
            HCl_Date_MLO,
            HCl_MLO,
            s=20,
            facecolors='none',
            edgecolors='navy',
            alpha=0.75,
            label=
            'Mauna Loa Observatory NDAC FTIR (19.54$^\circ$ N)\n {0:.2f} $\pm$ {1:.2f} %/yr'
            .format(res[1] / np.nanmean(HCl_MLO[inds]) * 100.0,
                    np.std(slope_b) / np.mean(HCl_MLO[inds]) * 100.0))

        axes[2].set_ylim(1.2, 5.3)
        axes[2].set_xlim(dt.date(1979, 1, 1), dt.date(2017, 12, 31))

        axes[2].set_ylabel(
            'Total Column [x10$^{15}$ molec/cm$^2$], FTIR (HCl)',
            color='blue',
            fontsize=14)
        axes[2].tick_params(axis='y', colors='blue', labelsize=14)

        axes[0].set_xlabel('Year', fontsize=14)

        fig.autofmt_xdate()
        fig.subplots_adjust(left=0.1, bottom=0.125, right=0.8, top=0.94)

        lines, labels = axes[0].get_legend_handles_labels()
        lines2, labels2 = axes[1].get_legend_handles_labels()
        lines3, labels3 = axes[2].get_legend_handles_labels()

        axes[0].legend(lines + lines2 + lines3,
                       labels + labels2 + labels3,
                       prop={'size': 10.5},
                       loc=2,
                       frameon=False,
                       ncol=2)  #'weight':'bold'

        plt.suptitle(
            'NH Inorganic Chlorine 1983 to 2016 (Trends 1997 to 2016)',
            fontsize=16)

        # #-----------------------------------------
        # #SAVE MLO DATA IN ASCII
        # #-----------------------------------------
        # YYYYMMDD = np.asarray(['{0:4d}-{1:02d}-{2:02d}'.format(HCl_Date_MLO[i].year, HCl_Date_MLO[i].month, HCl_Date_MLO[i].day)    for i,dum in enumerate(HCl_Date_MLO)])

        # with open('/data1/Campaign/Satellite/MLS/MLO_pltCly.ascii','w') as fopen:
        #     fopen.write('#Hannigan, J.W., Ortega, I\n')
        #     fopen.write('#National Center for Atmospheric Research\n')
        #     fopen.write('#Mauna Loa Observatory NDAC FTIR Monthly Data (19.54deg N)\n')
        #     fopen.write('#Mauna Loa smoothed data is included using a window of 24 (2 years)\n')
        #     fopen.write('#CONTACT_INFO: Hannigan, Jim, [email protected], 303-497-1853, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')
        #     fopen.write('#CONTACT_INFO: Ortega, Ivan, [email protected], 303-497-1861, NCAR, 3090 Center Green Drive, Boulder, CO 80301\n')

        #     fopen.write('Index, YYYY-MM-DD, HCl [[x10^15 molec/cm^2]], HCl_smooth [[x10$^15 molec/cm^2]]\n')
        #     strFormat = '{0:d}, {1:>10s},  {2:.3f}, {3:.3f}\n'

        #     for i,sngTime in enumerate(YYYYMMDD):
        #         fopen.write(strFormat.format((i+1),YYYYMMDD[i], HCl_MLO[i], HCl_MLO_smth[i]))

        if self.pdfsav:
            self.pdfsav.savefig(fig, dpi=200)
            if self.AgagefileID == 0:
                plt.savefig('/data1/Campaign/Satellite/MLS/Cly_all_Mace.pdf'
                            )  # bbox_inches='tight'
            if self.AgagefileID == 1:
                plt.savefig('/data1/Campaign/Satellite/MLS/Cly_all_Global.pdf'
                            )  # bbox_inches='tight'
        else:
            plt.draw()
            plt.show(block=False)
            user_input = raw_input('Press any key to exit >>> ')
            sys.exit()
コード例 #18
0
print "==============================================="

#=================================================== define the Plot:

fig, ax = plt.subplots(figsize=(16, 9))
plt.xlabel('Year', fontsize=16)
plt.ylabel('Surface Downwelling Solar Radiation ( W/m2 )', fontsize=16)
plt.title("Surface Downwelling Solar Radiation over the SWIO", fontsize=18)

# vertical range ylim yrange
plt.ylim(160, 300)
plt.yticks(np.arange(160, 300, 20))

plt.grid()

ax.xaxis.set_major_locator(MonthLocator(1))  # interval = 5
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))
ax.fmt_xdata = DateFormatter('%m')

#plt.xticks(np.arange(1950, 2016, 5))
#plt.tick_params(axis='both', which='major', labelsize=14)
#plt.tick_params(axis='both', which='minor', labelsize=14)

#=================================================== 3 windows
#plt.axvspan(1950, 1980, alpha=0.2, color='teal')
#plt.axvspan(1980, 2000, alpha=0.2, color='teal')
#plt.axvspan(2000, 2016, alpha=0.2, color='teal')
#=================================================== draw lines
#plt.axvline(x=2005,linewidth=2, color='gray')
plt.axhline(y=0, linewidth=2, color='gray')
コード例 #19
0
def stats_helper(request, software_id, type, dpi):
    # matplotlib needs a writable home directory
    if settings.PRODUCTION:
        import os
        os.environ['HOME'] = '/home/mloss/tmp'

    import matplotlib
    import datetime
    matplotlib.use('Cairo')
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
    from matplotlib.dates import DayLocator, WeekdayLocator, HourLocator, MonthLocator, YearLocator
    from matplotlib.dates import DateFormatter, date2num
    from StringIO import StringIO

    if dpi <= 40:
        bgcol = '#f7f7f7'
    else:
        bgcol = '#ffffff'
    fig = Figure(figsize=(8, 6), dpi=dpi, facecolor=bgcol)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)

    stat = SoftwareStatistics.objects.filter(
        software=software_id).distinct().order_by('date')

    if stat.count() <= 0:
        return HttpResponseForbidden()

    x = list()
    y = list()
    for entry in stat:
        x.append(date2num(entry.date))
        if type == 'downloads':
            y.append(entry.number_of_downloads)
        elif type == 'views':
            y.append(entry.number_of_views)

    #ax.plot(x,y,'bo', alpha=0.7)
    #ax.plot(x,y,'b-',linewidth=1, alpha=0.5)
    ax.bar(x, y)

    days = DayLocator()
    weeks = WeekdayLocator()
    months = MonthLocator()
    years = YearLocator()
    dateFmt = DateFormatter("%Y-%m-%d")
    ax.xaxis.set_major_formatter(dateFmt)

    if len(x) <= 14:
        ax.xaxis.set_major_locator(days)
    elif len(x) < 60:
        ax.xaxis.set_major_locator(weeks)
        ax.xaxis.set_minor_locator(days)
    elif len(x) < 720:
        ax.xaxis.set_major_locator(months)
        ax.xaxis.set_minor_locator(weeks)
    else:
        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_minor_locator(months)

    if dpi > 40:
        if type == 'downloads':
            ax.set_title('Number of Downloads')
            ax.set_ylabel('Downloads per Day')
        elif type == 'views':
            ax.set_title('Number of Views')
            ax.set_ylabel('Views per Day')

        ax.grid(True)
    ax.axis("tight")

    for label in ax.get_xticklabels():
        label.set_ha('right')
        label.set_rotation(30)

    canvas.draw()
    imdata = StringIO()
    fig.savefig(imdata, format='png', dpi=dpi, facecolor=bgcol)
    del fig
    del ax

    return HttpResponse(imdata.getvalue(), mimetype='image/png')
コード例 #20
0
def eg9_8():
    """
    9.8 动手实践:绘制全年股票价格
        我们可以使用matplotlib.finance包绘制全年的股票价格。获取数据源需要连接到雅虎
    财经频道。

    """
    # (1)将当前的日期减去1年作为起始日期。
    """
    from matplotlib.dates import DateFormatter
    from matplotlib.dates import DayLocator
    from matplotlib.dates import MonthLocator
    from matplotlib.finance import quotes_historical_yahoo
    from matplotlib.finance import candlestick
    import sys
    from datetime import date
    import matplotlib.pyplot as plt
    # 将这些库添加到开头
    """
    today = date.today()
    start = date(today.year - 1, today.month, today.day)
    print start, today

    # (2) 我们需要创建所谓的定位器(locator),这些来自matplotlib.dates包中的对象可以在
    # x轴上定位月份和日期。
    alldays = DayLocator()
    months = MonthLocator()
    # print alldays, months

    # (3) 创建一个日期格式化器(date formatter)以格式化x轴上的日期。该格式化器将创建一个
    # 字符串,包含简写的月份和年份。
    month_formatter = DateFormatter("%b %Y")
    # print month_formatter

    # (4) 从雅虎财经频道下载股价数据。
    apple = web.get_data_yahoo('AAPL', start, today)
    apple.head()
    # 修改apple的值,从【High Low Open Close Volume Adj_Close】变为【Open Close High Low Adj_Close】
    del apple['Volume']  # 永久删除'Volume'
    # 移动"Open"和"Close"到第一列和第二列
    cols = list(apple)
    cols.insert(0, cols.pop(cols.index('Open')))
    cols.insert(1, cols.pop(cols.index('Close')))
    apple = apple.ix[:, cols]
    print apple
    # 保存pandas DataFrame数据为csv
    apple.to_csv('output/AAPL.csv')
    # 1、读取行情数据文件
    df_stock = pd.read_csv('output/AAPL.csv', header=0, index_col=None)  # header=0表示第一行为列名
    print df_stock

    print df_stock.shape[0]
    # 2、构造传入数据的数据结构quotes
    # 画k线图需传的参数,包括(交易日时间戳,开盘价,收盘价,最高价,最低价)
    quotes = []
    # 构造要画k线图的数据结构,获取第一个日期时刻(20200424),将其转为数字值,后面每个日期-1
    date_plt = 0
    date_num = 0
    for i in range(df_stock.shape[0]):  # 遍历每行,shape为dataframe大小(x,y),表示x行y列
        if i == 0:
            # 将交易日期日期转为数字
            date_num = date2num(datetime.strptime(df_stock.ix[[i]].values[0][0], '%Y-%m-%d'))  # 1表示第一列,为交易日
            print df_stock.ix[[i]].values[0][0]
            print date_num
            date_plt = date_num
        else:
            print df_stock.ix[[i]].values[0][0]
            date_plt = date_num + i  # 由于csv文件中日期为升序排序,这里为加号
        print(df_stock.ix[[i]].values[0])       # 打印每行数据 ['000001-SZE' '2020-04-24' 13.17 13.28 13.11 13.24 56600161 747473770.46 nan]
        open = df_stock.ix[[i]].values[0][1]  # 开盘价: i行第2列  df_stock.iloc[i]['开盘价'],用这个似乎输出了的列对不上,输出成了下一列值(最高价)
        close = df_stock.ix[[i]].values[0][2]  # 收盘价:i行第3列
        high = df_stock.ix[[i]].values[0][3]  # 最高价:i行第4列
        low = df_stock.ix[[i]].values[0][4]  # 最低价:i行第5列
        datas = (date_plt, open, close, high, low)
        print(datas)                             # (737539.0, 13.17, 13.24, 13.28, 13.11)
        quotes.append(datas)

    # (5) 创建一个Matplotlib的figure对象——这是绘图组件的顶层容器。
    fig = plt.figure()

    # (6) 增加一个子图。
    ax = fig.add_subplot(111)

    # (7) 将x轴上的主定位器设置为月定位器。该定位器负责x轴上较粗的刻度。
    ax.xaxis.set_major_locator(months)

    # (8) 将x轴上的次定位器设置为日定位器。该定位器负责x轴上较细的刻度。
    ax.xaxis.set_minor_locator(alldays)

    # (9) 将x轴上的主格式化器设置为月格式化器。该格式化器负责x轴上较粗刻度的标签。
    ax.xaxis.set_major_formatter(month_formatter)

    # (10) matplotlib.finance包中的一个函数可以绘制K线图。这样,我们就可以使用获取的
    # 股价数据来绘制K线图。我们可以指定K线图的矩形宽度,现在先使用默认值。

    candlestick_ochl(ax, quotes)

    # (11) 将x轴上的标签格式化为日期。为了更好地适应x轴的长度,标签将被旋转。
    fig.autofmt_xdate()
    plt.show()
コード例 #21
0
merge_corr_df = pd.merge(merge_corr_df,
                         volume_corr_df,
                         how='left',
                         on=['Symbol'])
print(merge_corr_df)

# Generate graph for stocks value variation
fig, ax = plt.subplots()
symbols = set(df['Symbol'])
df['Date'] = pd.to_datetime(df['Date'])
for symbol in symbols:
    ax.plot(df[df.Symbol == symbol].Date,
            df[df.Symbol == symbol].Close,
            label=symbol)
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))
ax.xaxis.set_major_locator(MonthLocator(interval=3))
ax.set_xlabel("Date")
ax.set_ylabel("Close Price")
ax.legend()
plt.show()

# Part II: Pull 2017-08-03 to 2020-08-03 data fr YahooFinance for specific stock analysis

# Import libraries needed
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
from matplotlib import style

# Adjust style of matplotlib
style.use('ggplot')
コード例 #22
0
def eg9_18():
    """
    9.18 动手实践:使用图例和注释
        在第3章中我们学习了如何计算股价的指数移动平均线。我们将绘制一只股票的收盘价和对
    应的三条指数移动平均线。为了清楚地描述图像的含义,我们将添加一个图例,并用注释标明两
    条平均曲线的交点。部分重复的步骤将被略去。
    """
    # 加载苹果的股票信息,并转化成numpy
    df_stock = pd.read_csv('output/AAPL.csv', header=0, index_col=None)
    quotes = []
    for i in range(df_stock.shape[0]):  # 遍历每行,shape为dataframe大小(x,y),表示x行y列
        if i == 0:
            # 将交易日期日期转为数字
            date_num = date2num(datetime.strptime(df_stock.ix[[i]].values[0][0], '%Y-%m-%d'))  # 1表示第一列,为交易日
            date_plt = date_num
        else:
            date_plt = date_num + i  # 由于csv文件中日期为升序排序,这里为加号
        open = df_stock.ix[[i]].values[0][1]  # 开盘价: i行第2列
        close = df_stock.ix[[i]].values[0][2]  # 收盘价:i行第3列
        high = df_stock.ix[[i]].values[0][3]  # 最高价:i行第4列
        low = df_stock.ix[[i]].values[0][4]  # 最低价:i行第5列
        datas = (date_plt, open, close, high, low)
        quotes.append(datas)
    quotes = np.array(quotes)
    dates = quotes.T[0]
    close = quotes.T[2]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    # (1) 计算并绘制指数移动平均线:如果需要,请回到第3章中复习一下指数移动平均线的计算
    # 方法。分别使用9、12和15作为周期数计算和绘制指数移动平均线。
    emas = []
    for i in range(9, 18, 3):
        weights = np.exp(np.linspace(-1., 0., i))
        weights /= weights.sum()
        ema = np.convolve(weights, close)[i - 1:-i + 1]
        idx = (i - 6) / 3
        ax.plot(dates[i - 1:], ema, lw=idx, label="EMA(%s)" % (i))
        data = np.column_stack((dates[i - 1:], ema))
        emas.append(np.rec.fromrecords(data, names=["dates", "ema"]))

    # (2) 我们来找到两条指数移动平均曲线的交点。
    first = emas[0]["ema"].flatten()
    second = emas[1]["ema"].flatten()
    bools = np.abs(first[-len(second):] - second) / second < 0.0001
    xpoints = np.compress(bools, emas[1])

    # (3) 我们将找到的交点用注释和箭头标注出来,并确保注释文本在交点的不远处。
    for xpoint in xpoints:
        ax.annotate('x', xy=xpoint, textcoords='offset points',
                    xytext=(-50, 30),
                    arrowprops=dict(arrowstyle="->"))

    # (4) 添加一个图例并由Matplotlib自动确定其摆放位置。
    leg = ax.legend(loc='best', fancybox=True)

    # (5) 设置alpha通道值,将图例透明化。
    leg.get_frame().set_alpha(0.5)

    # (6) 显示图像
    alldays = DayLocator()
    months = MonthLocator()
    month_formatter = DateFormatter("%b %Y")
    ax.plot(dates, close, lw=1.0, label="Close")
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(month_formatter)
    ax.grid(True)
    fig.autofmt_xdate()
    plt.show()
コード例 #23
0
#plt.title(station,fontdict=font2, pad=14)#Title
plt.scatter(x1, y1, edgecolors=None, c='r', s=15, marker='s', label='Measured')
plt.plot(x2, y2, 'b-', lw=1.0, label="Model Output")  #Line
plt.axvline(x=datetime.date(2013, 1, 1), ls='--', c='black', lw=1.0)
plt.ylabel('Flow rate ($\mathregular{m^{3}}$/s)',
           fontdict=font2)  #$\mathregular{min^{-1}}$label的格式,^{-1}为上标
plt.xlabel('Time', fontdict=font2)
plt.legend(loc="upper left",
           scatterpoints=1,
           prop=font1,
           shadow=True,
           frameon=False)  #添加图例,
ax.set_xlim(datetime.date(1995, 1, 1), datetime.date(2014, 1, 1))
ax.set_ylim(0.0, 8.0)
# Major ticks every 12 months.
fmt_whole_year = MonthLocator(interval=12)
ax.xaxis.set_major_locator(fmt_whole_year)
date_form = DateFormatter(
    "%Y")  #only display year here, capital means 4 digits
ax.xaxis.set_major_formatter(date_form)
#ax.set_xticks(np.arange(datetime.date(1992,1,1), datetime.date(2014,1,2), step=datetime.timedelta(days=365.25)))
#plt.xticks(np.arange(datetime.date(1992,1,1), datetime.date(2014,1,2), step=datetime.timedelta(days=365.25)), rotation=45)
#ax.set_yticks(np.arange(datetime.date(1992,1,1), datetime.date(2014,1,1), step=365))
plt.text(0.40, 0.94, 'Train', fontdict=font2, transform=ax.transAxes)
plt.text(0.96, 0.94, 'Test', fontdict=font2, transform=ax.transAxes)

#plt.text(0.91, 0.92, '(a)', fontdict=text_font, transform = ax.transAxes)
#plt.text(0.91, 0.92, '(b)', fontdict=text_font, transform = ax.transAxes)
plt.text(0.86, 0.94, 'Station 1', fontdict=font2, transform=ax.transAxes)
plt.show()
コード例 #24
0
ファイル: mcp.py プロジェクト: evanescentstar/mcmath
def dateplt_m2(t,
               y,
               yl=5,
               fxlim=None,
               fylim=None,
               ticksize=10,
               nomth=True,
               fmt='+-',
               **kwargs):
    """Different from dateplt_m in that it's just a 2-digit year for x tick marks"""

    from matplotlib.dates import YearLocator, DateFormatter, MonthLocator
    xchange = 0
    ychange = 0
    fig = plt.gcf()
    ax = plt.gca()
    years = YearLocator(yl)
    yearsFmt = DateFormatter("'%y")
    if nomth == False:
        months = MonthLocator(1)

    if isinstance(y, np.ma.MaskedArray):
        data_extent = np.where(y.mask == False)
        if len(data_extent) < 2:
            data_start = 0
            data_end = y.size - 1
        else:
            data_start = data_extent[0][0]
            data_end = data_extent[0][-1]
    else:
        data_start = 0
        data_end = y.size - 1
    if (isinstance(t[0], np.float64) is True) or (isinstance(t[0], np.float32)
                                                  is True):
        datemin = num2date(t[data_start])
        datemax = num2date(t[data_end])
    elif isinstance(t[0], dt):
        datemin = t[data_start]
        datemax = t[data_end]
    else:
        return None

    datediff = datemax - datemin
    datediff = datediff / 50
    datemin = datemin - datediff
    datemax = datemax + datediff
    ymin = np.nanmin(y) - 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
    ymax = np.nanmax(y) + 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
    (oldymin, oldymax) = ax.get_ylim()
    (oldxmin, oldxmax) = ax.get_xlim()

    if (np.sign(ymax) != np.sign(ymin)):
        ax.axhline(0.0, c='black', lw=1.2, alpha=0.7)
    line1 = ax.plot(t, y, fmt, **kwargs)
    #	ax.set_xlim(datemin,datemax)
    ax.grid(True)

    if (datemin.toordinal() < oldxmin) | (oldxmin == 0.):
        xchange = 1
        oldxmin = datemin.toordinal()
    if datemax.toordinal() > oldxmax:
        xchange = 1
        oldxmax = datemax.toordinal()
    if ymin < oldymin:
        ychange = 1
        oldymin = ymin
    if ymax > oldymax:
        ychange = 1
        oldymax = ymax

    if (fylim is not None):
        if type(fylim) is not tuple:
            print "option <fylim> must be a tuple"
            return None
        (ymin, ymax) = fylim
        plt.setp(ax, ylim=ax.set_ylim(ymin, ymax))
    else:
        if xchange:
            plt.setp(ax, xlim=ax.set_xlim(oldxmin, oldxmax))
        if ychange:
            plt.setp(ax, ylim=ax.set_ylim(oldymin, oldymax))
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    if nomth == False:
        ax.xaxis.set_minor_locator(months)

    xtl = ax.get_xticklabels()
    ytl = ax.get_yticklabels()
    plt.setp(xtl, 'size', ticksize)
    plt.setp(ytl, 'size', ticksize)

    ##plt.show()

    ##my_fmt_xdate(ax,rot=45,hal='right')

    plt.figure(fig.number)
    return line1
コード例 #25
0
ファイル: date_demo1.py プロジェクト: wrgiannjr/matplotlib
you.  The dates module provides several converter functions date2num
and num2date

This example requires an active internet connection since it uses
yahoo finance to get the data for plotting
"""

from pylab import figure, show
from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
import datetime
date1 = datetime.date(1995, 1, 1)
date2 = datetime.date(2004, 4, 12)

years = YearLocator()  # every year
months = MonthLocator()  # every month
yearsFmt = DateFormatter('%Y')

quotes = quotes_historical_yahoo('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]

fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(dates, opens, '-')

# format the ticks
ax.xaxis.set_major_locator(years)
コード例 #26
0
ファイル: mcp.py プロジェクト: evanescentstar/mcmath
def dateplt1(t,
             y,
             add=None,
             yl=5,
             fxlim=None,
             fylim=None,
             fighold=False,
             nomth=True,
             **kwargs):
    from matplotlib.dates import YearLocator, DateFormatter, MonthLocator
    if add is None:
        ymin = np.nanmin(y) - 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
        ymax = np.nanmax(y) + 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
        if isinstance(y, np.ma.MaskedArray):
            data_extent = np.where(y.mask == False)
            if len(data_extent) < 2:
                data_start = 0
                data_end = y.size - 1
            else:
                data_start = data_extent[0][0]
                data_end = data_extent[0][-1]
        else:
            data_start = 0
            data_end = y.size - 1
        if (isinstance(t[0], np.float64) is True) or (isinstance(
                t[0], np.float32) is True):
            datemin = num2date(t[data_start])
            datemax = num2date(t[data_end])
        elif isinstance(t[0], dt):
            datemin = t[data_start]
            datemax = t[data_end]
        else:
            return None
        datediff = datemax - datemin
        datediff = datediff / 50
        datemin = datemin - datediff
        datemax = datemax + datediff
        if fighold is True:
            plt.hold(False)
            fig = plt.gcf()
            plt.clf()
        else:
            fig = plt.figure()
        if (fylim is not None):
            if type(fylim) is not tuple:
                print "option <fylim> must be a tuple"
                return None
            (ymin, ymax) = fylim
        ax = fig.add_subplot(111, autoscale_on=False, ylim=(ymin, ymax))
        if (np.sign(ymax) != np.sign(ymin)):
            ax.axhline(0.0, c='black', lw=1.2, alpha=0.7)
        line1 = ax.plot(t, y, '+-', **kwargs)
        years = YearLocator(yl)
        yearsFmt = DateFormatter('%Y')
        if nomth == False:
            months = MonthLocator(1)

        ax.set_xlim(datemin, datemax)

        #fig.autofmt_xdate()
        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(yearsFmt)
        if nomth == False:
            ax.xaxis.set_minor_locator(months)

        ax.grid(True)
        my_fmt_xdate(ax)
        ##plt.show()
        ##ylabel('temperature anomaly')
        plt.figure(fig.number)
        return line1

    else:
        xchange = 0
        ychange = 0
        fig = plt.gcf()
        ax = plt.gca()
        years = YearLocator(yl)
        yearsFmt = DateFormatter('%Y')
        months = MonthLocator(1)
        line1 = ax.plot(t, y, '+-', **kwargs)
        if isinstance(y, np.ma.MaskedArray):
            data_extent = np.where(y.mask == False)
            if len(data_extent) == 0:
                data_start = 0
                data_end = y.size - 1
            else:
                data_start = data_extent[0][0]
                data_end = data_extent[0][-1]
        else:
            data_start = 0
            data_end = y.size - 1
        if (isinstance(t[0], np.float64) is True) or (isinstance(
                t[0], np.float32) is True):
            datemin = num2date(t[data_start])
            datemax = num2date(t[data_end])
        elif isinstance(t[0], dt):
            datemin = t[data_start]
            datemax = t[data_end]
        else:
            return None

        datediff = datemax - datemin
        datediff = datediff / 50
        datemin = datemin - datediff
        datemax = datemax + datediff
        ymin = np.nanmin(y) - 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
        ymax = np.nanmax(y) + 0.02 * (abs(np.nanmax(y) - np.nanmin(y)))
        (oldymin, oldymax) = ax.get_ylim()
        (oldxmin, oldxmax) = ax.get_xlim()

        if (fylim is not None):
            if type(fylim) is not tuple:
                print "option <fylim> must be a tuple"
                return None
            (ymin, ymax) = fylim
        if datemin.toordinal() < oldxmin:
            xchange = 1
            oldxmin = datemin.toordinal()
        if datemax.toordinal() > oldxmax:
            xchange = 1
            oldxmax = datemax.toordinal()
        if ymin < oldymin:
            ychange = 1
            oldymin = ymin
        if ymax > oldymax:
            ychange = 1
            oldymax = ymax
        if xchange:
            plt.setp(ax, xlim=ax.set_xlim(oldxmin, oldxmax))
        if ychange:
            plt.setp(ax, ylim=ax.set_ylim(oldymin, oldymax))
        ax.xaxis.set_major_locator(years)
        ax.grid(True)
        my_fmt_xdate(ax)
        plt.figure(fig.number)
        return line1
コード例 #27
0
print("done")

###############################################################################
# Print trained parameters and plot
print("Transition matrix")
print(model.transmat_)
print()

print("Means and vars of each hidden state")
for i in range(model.n_components):
    print("{0}th hidden state".format(i))
    print("mean = ", model.means_[i])
    print("var = ", np.diag(model.covars_[i]))
    print()

fig, axs = plt.subplots(model.n_components, sharex=True, sharey=True)
colours = cm.rainbow(np.linspace(0, 1, model.n_components))
for i, (ax, colour) in enumerate(zip(axs, colours)):
    # Use fancy indexing to plot data in each state.
    mask = hidden_states == i
    ax.plot_date(dates[mask], close_v[mask], ".-", c=colour)
    ax.set_title("{0}th hidden state".format(i))

    # Format the ticks.
    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_minor_locator(MonthLocator())

    ax.grid(True)

plt.show()
コード例 #28
0
ファイル: grappher.py プロジェクト: taoprajjwal/NBAGrapher
def plot_player_game(players,
                     season,
                     stat,
                     start_date=datetime.date(1900, 1, 1),
                     end_date=datetime.date(3000, 1, 1),
                     only_month=False,
                     xlabel="Time",
                     ylabel=None,
                     scatter=True,
                     return_type="img",
                     cum=False):
    """
    Uses Sportsreference
    Plots the graphs of players according to their performance in particular games.

    :param players: Basketball-reference id of a player or list of players
    :type players: String or list of strings
    :param season: The season in which the games are played
    :type season: Either in dashed form (2018-19) or single form (2019 means the season 2018-19)
    :param stat: The statistical attribute of the player to plot
    :type stat: String
    :param start_date: The date from which the data is plotted
    :type start_date: datetime.date format
    :param end_date: The date untill which data is plotted
    :type end_date: datetime.date format
    :param only_month: Wheter or not the ticks on the x-axis only contain months. (Recommended when plotting dates extending across dates more than a couple of months)
    :type only_month: Bool
    :param xlabel: The label on the x-axis on the returned plot
    :type xlabel: String
    :param ylabel: The label on the x-axis on the returned plot
    :type ylabel: String
    :param scatter: Wheter on not to include a dot for each data point in the graph
    :type scatter: Bool
    :param return_type: Various methods by which the graph can be returned
    :type return_type: "img": png image, "fig":Matplotlib figure and axes,"show": calls the matplotlib show function (appropriate for jupyter notebooks), "html": base64 image useful for rendering in html pages
    :param cum: Wheter results are cumulative or not
    :type cum: Bool

    """
    if type(players) is not list:
        players = [players]

    player_obj = get_player_obj(players)

    fig, ax = plt.subplots()
    for player in player_obj:
        season = date_format(season)
        team = player(season).team_abbreviation
        sch = Schedule(team, date_format(season, format_as="single"))
        sch_df = sch.dataframe
        x = []
        y = []
        for index, row in sch_df.iterrows():
            if start_date <= row['datetime'].date() <= end_date:
                box = Boxscore(index)
                if row['location'] == "Home":
                    for boxplay in box.home_players:
                        if boxplay.player_id == player.player_id:
                            x.append(row['datetime'].date())
                            if cum:
                                try:
                                    prev = y[-1]
                                except:
                                    prev = 0
                                y.append(boxplay.dataframe[stat] + prev)
                            else:
                                y.append(boxplay.dataframe[stat])
                elif row['location'] == "Away":
                    for boxplay in box.away_players:
                        if boxplay.player_id == player.player_id:
                            x.append(row['datetime'].date())
                            if cum:
                                try:
                                    prev = y[-1]
                                except:
                                    prev = 0
                                y.append(boxplay.dataframe[stat] + prev)
                            else:
                                y.append(boxplay.dataframe[stat])
        ax.plot(x, y, label=player.name)
        if scatter:
            ax.scatter(x, y)
        ax.legend()
        if only_month:
            ax.xaxis.set_major_locator(MonthLocator())
            ax.xaxis.set_major_formatter(DateFormatter("%y-%m"))

    fig.autofmt_xdate()

    ax.set_xlabel(xlabel)
    if ylabel == None:
        ylabel = stat
    ax.set_ylabel(ylabel)

    return return_plot(stat, fig, ax, return_type)
コード例 #29
0
ファイル: forecaster.py プロジェクト: yunweidashuju/prophet
    def plot_components(self, fcst, uncertainty=True):
        """Plot the Prophet forecast components.

        Will plot whichever are available of: trend, holidays, weekly
        seasonality, and yearly seasonality.

        Parameters
        ----------
        fcst: pd.DataFrame output of self.predict.
        uncertainty: Optional boolean to plot uncertainty intervals.

        Returns
        -------
        a matplotlib figure.
        """
        # Identify components to be plotted
        plot_trend = True
        plot_holidays = self.holidays is not None
        plot_weekly = 'weekly' in fcst
        plot_yearly = 'yearly' in fcst

        npanel = plot_trend + plot_holidays + plot_weekly + plot_yearly
        forecast_color = '#0072B2'
        fig = plt.figure(facecolor='w', figsize=(9, 3 * npanel))
        panel_num = 1
        ax = fig.add_subplot(npanel, 1, panel_num)
        ax.plot(fcst['ds'].values, fcst['trend'], ls='-', c=forecast_color)
        if 'cap' in fcst:
            ax.plot(fcst['ds'].values, fcst['cap'], ls='--', c='k')
        if uncertainty:
            ax.fill_between(fcst['ds'].values,
                            fcst['trend_lower'],
                            fcst['trend_upper'],
                            color=forecast_color,
                            alpha=0.2)
        ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
        ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
        ax.set_xlabel('ds')
        ax.set_ylabel('trend')

        if plot_holidays:
            panel_num += 1
            ax = fig.add_subplot(npanel, 1, panel_num)
            holiday_comps = self.holidays['holiday'].unique()
            y_holiday = fcst[holiday_comps].sum(1)
            y_holiday_l = fcst[[h + '_lower' for h in holiday_comps]].sum(1)
            y_holiday_u = fcst[[h + '_upper' for h in holiday_comps]].sum(1)
            # NOTE the above CI calculation is incorrect if holidays overlap
            # in time. Since it is just for the visualization we will not
            # worry about it now.
            ax.plot(fcst['ds'].values, y_holiday, ls='-', c=forecast_color)
            if uncertainty:
                ax.fill_between(fcst['ds'].values,
                                y_holiday_l,
                                y_holiday_u,
                                color=forecast_color,
                                alpha=0.2)
            ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
            ax.xaxis.set_major_locator(MaxNLocator(nbins=7))
            ax.set_xlabel('ds')
            ax.set_ylabel('holidays')

        if plot_weekly:
            panel_num += 1
            ax = fig.add_subplot(npanel, 1, panel_num)
            df_s = fcst.copy()
            df_s['dow'] = df_s['ds'].dt.weekday_name
            df_s = df_s.groupby('dow').first()
            days = pd.date_range(start='2017-01-01', periods=7).weekday_name
            y_weekly = [df_s.loc[d]['weekly'] for d in days]
            y_weekly_l = [df_s.loc[d]['weekly_lower'] for d in days]
            y_weekly_u = [df_s.loc[d]['weekly_upper'] for d in days]
            ax.plot(range(len(days)), y_weekly, ls='-', c=forecast_color)
            if uncertainty:
                ax.fill_between(range(len(days)),
                                y_weekly_l,
                                y_weekly_u,
                                color=forecast_color,
                                alpha=0.2)
            ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
            ax.set_xticks(range(len(days)))
            ax.set_xticklabels(days)
            ax.set_xlabel('Day of week')
            ax.set_ylabel('weekly')

        if plot_yearly:
            panel_num += 1
            ax = fig.add_subplot(npanel, 1, panel_num)
            df_s = fcst.copy()
            df_s['doy'] = df_s['ds'].map(lambda x: x.strftime('2000-%m-%d'))
            df_s = df_s.groupby('doy').first().sort_index()
            ax.plot(pd.to_datetime(df_s.index),
                    df_s['yearly'],
                    ls='-',
                    c=forecast_color)
            if uncertainty:
                ax.fill_between(pd.to_datetime(df_s.index),
                                df_s['yearly_lower'],
                                df_s['yearly_upper'],
                                color=forecast_color,
                                alpha=0.2)
            ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
            months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
            ax.xaxis.set_major_formatter(DateFormatter('%B %-d'))
            ax.xaxis.set_major_locator(months)
            ax.set_xlabel('Day of year')
            ax.set_ylabel('yearly')

        fig.tight_layout()
        return fig
コード例 #30
0
        databounds['min_v'] = args.manual_databounds[0]
        databounds['max_v'] = args.manual_databounds[1]

    ax2 = plt.gca()
    ax2.set_ylim(databounds['min_v'], databounds['max_v'])
    ax2.set_xlim([databounds['min_t'], databounds['max_t']])

    if not legend_off:
        leg = ax2.legend(label_thin, loc=legend_loc, ncol=6, fontsize=8)
        for legobj in leg.legendHandles:
            legobj.set_linewidth(2.0)

    plt.ylabel(Ylabel)
    if LocatorInterval == 'multi_year':
        ax2.xaxis.set_major_locator(YearLocator())
        ax2.xaxis.set_minor_locator(MonthLocator(bymonth=6))
        ax2.xaxis.set_major_formatter(ticker.NullFormatter())
        ax2.xaxis.set_minor_formatter(DateFormatter('%Y'))
        ax2.tick_params(axis='both', which='minor', labelsize=12)
    else:
        ax2.xaxis.set_major_locator(MonthLocator())
        ax2.xaxis.set_minor_locator(
            MonthLocator(bymonth=[1, 3, 5, 7, 9, 11], bymonthday=15))
        ax2.xaxis.set_major_formatter(ticker.NullFormatter())
        ax2.xaxis.set_minor_formatter(DateFormatter('%b %y'))
        ax2.tick_params(axis='both', which='minor', labelsize=12)

    t = fig.suptitle(ptitle, fontsize=8)
    t.set_y(0.03)

    #fig.autofmt_xdate()