Пример #1
0
    def __init__(self, readers, **kwargs):
        f = bop.figure(tooltips=[('', '$data_y')])
        p = registry.parse_prefix(readers[0].prefix)
        f.title = bom.Title(text=p.group)
        default_tools(f)

        self.figure = f
Пример #2
0
    def __init__(self, readers, **kwargs):

        self.readers = readers
        self.source = bom.ColumnDataSource(self.combined())

        f = bop.figure(tooltips=[('', '$data_y')])

        for reader, color in zip(readers, cycle(Category10_10)):
            p = registry.parse_prefix(reader.prefix)
            label = dict(legend_label=p.label) if p.label else dict()
            f.line(x=f'{reader.prefix}.x',
                   y=f'{reader.prefix}.y',
                   color=color,
                   source=self.source,
                   **label)
            f.circle(x=f'{reader.prefix}.x',
                     y=f'{reader.prefix}.y',
                     color=color,
                     source=self.source,
                     **label)

        f.title = bom.Title(text=p.group)
        default_tools(f)

        self.figure = f
Пример #3
0
    def __init__(self, readers, rule):
        [self.reader] = readers
        self.rule = rule

        aligned = self.aligned()
        self.source = bom.ColumnDataSource(aligned)

        f = bop.figure(x_range=bom.DataRange1d(start=0,
                                               follow='end',
                                               range_padding=0),
                       y_range=bom.DataRange1d(start=0),
                       tooltips=[('', '$data_y')])

        p = registry.parse_prefix(self.reader.prefix)
        n_bands = aligned.shape[1] - 1
        assert n_bands % 2 == 1
        for i in range(n_bands):
            color = Viridis256[255 - 256 * i // n_bands]
            lower = aligned.columns[i + 1]
            f.line(x='_time', y=f'{lower}', color=color, source=self.source)

        default_tools(f)
        styling(f)
        p = registry.parse_prefix(readers[0].prefix)
        f.title = bom.Title(text=p.group)

        self.figure = f
Пример #4
0
    def __init__(self, readers, rule):
        self.readers = readers
        self.rule = rule

        self.source = bom.ColumnDataSource(self.aligned())

        f = bop.figure(x_range=bom.DataRange1d(start=0, follow='end'),
                       tooltips=[('', '$data_y')])

        for reader, color in zip(readers, cycle(Category10_10)):
            p = registry.parse_prefix(reader.prefix)
            label = dict(legend_label=p.label) if p.label else dict()
            f.varea(x='_time',
                    y1=f'{reader.prefix}.μ-',
                    y2=f'{reader.prefix}.μ+',
                    color=color,
                    alpha=.2,
                    source=self.source,
                    **label)
            f.line(x='_time',
                   y=f'{reader.prefix}.μ',
                   color=color,
                   source=self.source,
                   **label)

        default_tools(f)
        x_zeroline(f)
        styling(f)
        p = registry.parse_prefix(readers[0].prefix)
        if p.label:
            legend(f)
        f.title = bom.Title(text=p.group)

        self.figure = f
Пример #5
0
    def _init(self, df):
        self._source = bom.ColumnDataSource(df.reset_index())

        children = []
        for name, group in timegroups(df).groupby('chart'):
            if group.label.eq('').all():
                assert len(group) == 1
                f = _timeseries(self._source, 'time', group.index[0])
                f.title = bom.Title(text=name)
            else:
                f = _timedataframe(self._source, 'time', group.index)
                f.title = bom.Title(text=name)
            children.append(f)
        self._grid = self._new_grid(children)
        ## TODO: Not wild about this
        clear_output(wait=True)
        self._handle = bop.show(self._grid, notebook_handle=True)
Пример #6
0
def preparePlot():
    coinTypes = ["Maple", "Phil", "Kang", "Krueger"]
    colors = itertools.cycle(palettes)
    pl.output_file("graph.html", title="GoldWatch")

    p = pl.figure(title="Preisverlauf verschiedener Goldmünzen (basierend auf den Daten von https://www.exchange-ag.de/)",plot_width=1000, x_axis_type="datetime")
    datetime = md.DatetimeTickFormatter(days="%d/%m %H:%M", months="%d/%m %H:%M", hours="%d/%m %H:%M", minutes="%d/%m %H:%M")
    p.xaxis.formatter = datetime
    p.add_layout(md.Title(text="Zeitpunkt der Datenerfassung", align="center"), "below")
    p.add_layout(md.Title(text="Goldpreis in €", align="center"), "left")

    tooltip = [
        ("Münztyp", "$name"),
        ("Datum", "$x"),
        ("Wert in €", "$y{int}")
    ]
    formatters = { "@x": "datetime"}
    p.add_tools(md.HoverTool(tooltips=tooltip, formatters=formatters))
    for coin,color in zip(coinTypes,colors):
        data = db_handler.getData(coin)
        tmp = ()
        x = []
        yB = []
        yS = []
        for idx,elem in enumerate(data):
            nTime = time.ctime(elem[0])
            
            x.append(dt.datetime.fromtimestamp(elem[0]))
            yB.append(elem[1])
            yS.append(elem[2])
            # nTime = time.s
        print(x,yB)
        p.line(x, yB, legend_label=f"{coin} Buy", line_color=color, line_width=2, name=f"{coin} Buy")
        p.line(x, yS, legend_label=f"{coin} Sell", line_color=color, line_width=2, line_dash="dashed", name=f"{coin} Sell")

    pl.save(p)
Пример #7
0
    def build(self):
        '''constructs the main layout'''
        self.doc.title = "Covid-19 Graphs"

        self.entities_layout = lyt.column([], width_policy="max")
        self.build_entity_ui_rows(self.entities_layout)
        self.add_entity_layout = self.build_add_entity_layout()
        self.options_layout = self.build_options_layout()
        self.sources_layout = self.build_sources_layout()

        # Make tabs
        self.view_tab = mdl.Panel(child=self.entities_layout,
                                  title='View/Remove')
        self.add_tab = mdl.Panel(child=self.add_entity_layout, title='Add')
        self.options_tab = mdl.Panel(child=self.options_layout,
                                     title='Options')
        self.sources_tab = mdl.Panel(child=self.sources_layout, title='Info')
        self.tabs = mdl.Tabs(tabs=[
            self.view_tab, self.add_tab, self.options_tab, self.sources_tab
        ])
        for tab in self.tabs.tabs:
            tab.child.width_policy = 'min'
        self.tabs.width_policy = 'min'

        # Create a row layout for tabs + plot

        # actual plot will be replace by make_plot when we have data, and
        # are ready to draw
        self.plot = bokeh.plotting.figure(title="Dummy placeholder plot")
        self.updated = mdl.Title(text=self.UPDATE_FETCHING,
                                 align="right",
                                 text_font_size="8pt",
                                 text_font_style="normal")
        self.plot.add_layout(self.updated, "below")

        self.controls_plot = mdl.Row(self.tabs, self.plot)
        self.controls_plot.sizing_mode = "stretch_both"

        self.save_button = self.build_save_button()
        self.main_layout = mdl.Column(self.controls_plot,
                                      self.save_button,
                                      sizing_mode='stretch_both')
        self.doc.add_root(self.main_layout)

        self.add_updated_local_time_callback()
Пример #8
0
def station_bar_plot(summary_csv, layer, out_dir=None, x_label=None, 
        y_label=None, title=None, subtitle=None, year_subtitle=True):
    """
    Produce an interactive bar chart comparing multiple climate stations to each
    other for a particular variable, e.g. bias ratios or interpolated residuals.
    
    Arguments:
        summary_csv (str): path to summary CSV produced by either :func:`gridwxcomp.calc_bias_ratios`
            or by :func:`gridwxcomp.interpolate`. Should contain ``layer`` 
            data for plot.
        layer (str): name of variable to plot.
    
    Keyword Arguments:
        out_dir (str or None): default None. Output directory path, default is 
            'station_bar_plots' in parent directory of ``summary_csv``.
        x_label (str or None): default None. Label for x-axis.
        y_label (str or None): default None. Label for y-axis, defaults to 
            ``layer``.
        title (str or None): default None. Title of plot.
        subtitle (str, list, or None): default None. Additional subtitle(s) 
            for plot.
        year_subtitle (bool): default True. If true print subtitle on plot with
            the max year range used for station data, e.g. 'years: 1995-2005'
            
    Example:
        Let's say we want to compare the mean growing seasion bias ratios of 
        reference evapotranspiration (ETr) for the selection of stations we 
        used to calculate bias ratios. The summary CSV file containing the 
        ratios should be first created using :func:`gridwxcomp.calc_bias_ratios`.
        
        >>> from gridwxcomp.plot import station_bar_plot
        >>> # path to summary CSV with station data
        >>> in_file = 'monthly_ratios/etr_mm_summary_all_yrs.csv'
        >>> layer = 'growseason_mean' 
        >>> station_bar_plot(in_file, layer)
        
        The resulting file will be saved using the layer name as a file name::
        
            'monthly_ratios/station_bar_plots/growseason_mean.html'
            
        The plot file will contain the mean growing season bias ratios 
        of ETr for each station, sorted from smallest to largest values. 
        
        This function may also be used for any numerical data in the summary CSV
        files that are created by :func:`gridwxcomp.interpolate` in addition to
        those created by :func:`gridwxcomp.calc_bias_ratios`. The main  
        requirement is that ``summary_csv`` must contain the column 'STATION_ID'
        and the ``layer`` keyword argument.
        
    Raises:
        FileNotFoundError: if ``summary_csv`` is not found.
        KeyError: if ``layer`` does not exist as a column name in ``summary_csv``.
        
    """
    if not Path(summary_csv).is_file():
        err_msg = '\n{} is not a valid path to a summary CSV file!'.\
                format(summary_csv)
        raise FileNotFoundError(err_msg)
        
    df = pd.read_csv(summary_csv, na_values=[-999])
    
    if not layer in df.columns:
        err_msg = '\nColumn {} was not found in {}'.format(layer, summary_csv)
        raise KeyError(err_msg)
    
    df.sort_values(layer, inplace=True)
    df.index.name = 'dummy_name' # fix internal to bokeh- reset_index 
    source = ColumnDataSource(df)
    # hover tooltip with station and value
    tooltips = [
        ("station", "@STATION_ID"),
        ("value", "@{}".format(layer)), 
    ]
    hover = models.HoverTool(tooltips=tooltips)
    
    if not y_label:
        y_label = layer
    # save to working directory in 'station_bar_plots' if not specified
    if not out_dir:
        out_dir = Path(summary_csv).parent/'station_bar_plots'
    else:
        out_dir = Path(out_dir)
    if not out_dir.is_dir():
        print('\n{}\nDoes not exist, making directory'.format(
            out_dir.absolute()))
        out_dir.mkdir(parents=True, exist_ok=True)

    out_file = out_dir/'{}.html'.format(layer)
    print('\nCreating station bar plot for variable: ', layer,
         '\nUsing data from file: ', Path(summary_csv).absolute())
    
    output_file(out_file)
    
    p = figure(x_range=df.STATION_ID, y_axis_label=y_label, title=title)
    p.vbar(x='STATION_ID', top=layer, width=0.8, source=source)
    p.xaxis.major_label_orientation = pi/2
    p.add_tools(hover, models.BoxSelectTool())
    
    if year_subtitle:
        # add data range (years start to end) as subtitle 
        min_yr = int(df.start_year.min())
        max_yr = int(df.end_year.max())
        if min_yr == max_yr:
            year_str = 'year: {}'.format(min_yr)
        else:
            year_str = 'years: {}-{}'.format(min_yr, max_yr)
        # caution note if not all stations use full year range
        if not (df.end_year==max_yr).all() or not (df.start_year==min_yr).all():
            year_str = '{} (less years exist for some stations)'.\
                    format(year_str)
            
        p.add_layout(models.Title(text=year_str, text_font_style="italic"), 
                'above')
    # add arbitrary number of custom subtitles as lines above plot 
    if isinstance(subtitle, (list, tuple)):
        for st in subtitle:
            p.add_layout(models.Title(text=st, text_font_style="italic"), 
                    'above')
    elif subtitle:
        p.add_layout(models.Title(text=subtitle, text_font_style="italic"), 
                'above')
        
    save(p)
    print('\nPlot saved to: ', out_file.absolute())