Ejemplo n.º 1
0
def lower_plot(df, p1):
    # configure wheelzoom tool
    wz = WheelZoomTool()
    wz.maintain_focus = False
    wz.dimensions = 'width'
    wz.zoom_on_axis = True

    p2_tools = 'box_zoom,pan,save, hover, reset'
    p2 = figure(width=fwidth,
                height=fhgt + 35,
                x_axis_type="datetime",
                tools=p2_tools,
                x_range=p1.x_range)
    p2.add_tools(wz)
    p2.min_border_top = fborder
    p2.min_border_bottom = fborder

    # pressure
    h_line = p2.line(x='time',
                     y='p',
                     source=df,
                     line_width=4,
                     color=pcol,
                     legend='Pressure')
    p2.y_range = Range1d(df['p'].min() - 5, df['p'].max() + 5)
    p2.yaxis.axis_label = 'Pressure (hPa)'

    # wind
    p2.extra_y_ranges = {
        "winddir": Range1d(start=0, end=360),
        "windspd": Range1d(start=0, end=df['ff'].max() + df['ff'].max() * 0.1)
    }

    p2.add_layout(
        LinearAxis(y_range_name='winddir',
                   ticker=SingleIntervalTicker(interval=45,
                                               num_minor_ticks=3)), 'right')
    p2.add_layout(LinearAxis(y_range_name="windspd"), 'right')
    p2.circle(x='time',
              y='dd',
              source=df,
              line_width=4,
              color='black',
              y_range_name='winddir',
              legend='Wind Direction')
    p2.line(x='time',
            y='ff',
            source=df,
            line_width=4,
            color=ffcol,
            y_range_name='windspd',
            legend='Wind speed')

    p2.yaxis[0].axis_label = 'Pressure (hPa)'
    p2.yaxis[1].axis_label = 'Wind direction (°)'
    p2.yaxis[2].axis_label = 'Wind speed (m s⁻¹)'
    p2.xaxis[0].axis_label = 'Time (UTC)'

    p2.yaxis[2].major_label_text_color = ffcol
    p2.yaxis[2].axis_label_text_color = ffcol
    p2.yaxis[2].minor_tick_line_color = ffcol
    p2.yaxis[2].major_tick_line_color = ffcol
    p2.yaxis[2].axis_line_color = ffcol
    p2.yaxis[0].major_label_text_color = pcol
    p2.yaxis[0].axis_label_text_color = pcol
    p2.yaxis[0].minor_tick_line_color = pcol
    p2.yaxis[0].major_tick_line_color = pcol
    p2.yaxis[0].axis_line_color = pcol

    # hover
    hover_p2 = p2.select(dict(type=HoverTool))
    hover_p2.tooltips = [("Timestamp", "@time{%d %b %Y %H:%M} UTC"),
                         ('Pressure', '@p{f0.0} hPa'),
                         ('Winddirection', '@dd{int} °'),
                         ('Windspeed', '@ff{f0.0} (m s⁻¹)')]
    hover_p2.formatters = {"time": "datetime"}
    hover_p2.mode = 'vline'
    hover_p2.renderers = [h_line]  #### to fix if missing value

    # legend
    p2.legend.location = (0, 15)  # above plot
    p2.legend.orientation = 'horizontal'
    p2.legend.click_policy = "hide"
    p2.legend.label_text_font_size = font_size_legend
    p2.add_layout(p2.legend[0], 'above')

    # font style
    p2 = set_font_style_axis(p2)

    #set boarders for zoom
    p2.x_range.max_interval = timedelta(7.5)
    return p2
Ejemplo n.º 2
0
def line(
    df_in: pd.DataFrame,
    *args,
    plot_height: int = 500,
    plot_width: int = 1400,
    toolbar_location: str = 'below',
    legend_location: str = 'right',
    **kwargs,
) -> figure:
    """Lineplot in bokeh."""
    #df = df.reset_index()
    df = df_in.copy()
    if isinstance(df, pd.Series):
        df = pd.DataFrame(df)
        df.columns = ['data']
    if 'datetime' in df.columns:
        df = df.drop('datetime', axis=1)

    df.index.name = None

    for column in df.columns:
        if df[column].dtypes == 'object':
            for index, category in enumerate(
                    df[column].astype('category').cat.categories):
                print(index, category)
            df[column] = df[column].astype('category').cat.codes

    df_cds = ColumnDataSource(df)

    p = figure(
        x_axis_type='datetime',
        plot_height=plot_height,
        plot_width=plot_width,
        title='',
        x_axis_label='timestamp',
        y_axis_label='value',
        toolbar_location=toolbar_location,
        tools="reset,box_zoom",
        # buggy:
        # x_range=DataRange1d(
        #     # df.index[0],
        #     # df.index[-1],
        #     bounds=(df.index[0] - dt.timedelta(weeks=52),
        #             df.index[-1] + dt.timedelta(weeks=52)), ),
        x_range=DataRange1d(bounds='auto'),
    )

    col_num = 0
    colors = color(len(df.columns))
    legends = []
    tooltips = []
    for column in df.columns:
        r = p.line(
            x='index',
            y=column,
            name='value',
            color=colors[col_num],
            source=df_cds,
        )
        col_num += 1

        legends.append((column, [r]))

        tooltips.append((column, '@{%s}' % column))

    tooltips.append(('index', '@index{%F}'))

    p.add_tools(
        HoverTool(
            tooltips=tooltips,
            renderers=[r],
            mode='vline',
            point_policy='follow_mouse',
            line_policy='none',
            formatters={'index': 'datetime'},
        ))

    legend = Legend(items=legends, location=(0, 0))

    p.add_tools(CrosshairTool())

    wheel_zoom_tool = WheelZoomTool()
    wheel_zoom_tool.dimensions = 'width'
    p.add_tools(wheel_zoom_tool)
    p.toolbar.active_scroll = wheel_zoom_tool

    pan_tool = PanTool()
    pan_tool.dimensions = 'width'
    p.add_tools(pan_tool)

    p.add_layout(legend, legend_location)

    p.legend.click_policy = 'hide'

    show(p)

    return p
Ejemplo n.º 3
0
def upper_plot(df):
    # configure wheelzoom tool
    wz = WheelZoomTool()
    wz.maintain_focus = False
    wz.dimensions = 'width'
    wz.zoom_on_axis = True

    p1_tools = 'box_zoom,pan,save, hover, reset'  #, xwheel_zoom' # zoom bounds auto?
    p1 = figure(width=fwidth,
                height=fhgt,
                x_axis_type="datetime",
                tools=p1_tools)
    p1.x_range = Range1d(start=df.index[-1] - timedelta(days=1),
                         end=df.index[-1],
                         bounds=(df.index[0], df.index[-1]))
    p1.add_tools(wz)
    p1.min_border_top = fborder
    p1.min_border_bottom = fborder

    # hover for temp, dew point and rel. humidity
    hover_p1 = p1.select(dict(type=HoverTool))
    hover_p1.tooltips = [("Timestamp", "@time{%d %b %Y %H:%M} UTC"),
                         ('Temperature', "@tl{f0.0} °C")]  #
    if 'tp' in df.columns:
        hover_p1[0].tooltips.append(('Dewpoint', '@tp{f0.0} °C'))
    else:

        hover_p1[0].tooltips.append(('Relative Humidity', '@rf{f0.0} %'))

    # sunshine duration
    if 'so' in df.columns:
        if ssdcum:
            varso = 'ssd_cum'  # 'ssd_cum' or 'so'
            unitso = 'h'
        else:
            varso = 'so'  # 'ssd_cum' or 'so'
            unitso = 'min'

        if ssdcum and df[varso].sum(
        ) > 0:  #axis would disappear when there was no rain measured
            p1.extra_y_ranges[varso] = Range1d(start=0,
                                               end=(df[varso].max() +
                                                    df[varso].max() * 0.1))
        else:
            p1.extra_y_ranges[varso] = Range1d(start=0, end=10)
        p1.add_layout(LinearAxis(y_range_name=varso), 'right')

        if ssdcum:
            p1.line(x='time',
                    y=varso,
                    source=df,
                    line_width=4,
                    color=socol,
                    y_range_name=varso,
                    legend='Sunshine duration (24h)')
        else:
            p1.vbar(top=varso,
                    x='time',
                    source=df,
                    width=get_width(),
                    fill_color=socol,
                    line_alpha=0,
                    line_width=0,
                    fill_alpha=0.5,
                    y_range_name=varso,
                    legend='Sunshine duration')

        p1.yaxis[1].axis_label = 'Sunshine duration (' + unitso + ')'
        p1.yaxis[1].axis_label_text_font_size = font_size_label

        p1.yaxis[1].major_label_text_color = socol
        p1.yaxis[1].axis_label_text_color = socol
        p1.yaxis[1].minor_tick_line_color = socol
        p1.yaxis[1].major_tick_line_color = socol
        p1.yaxis[1].axis_line_color = socol
        hover_p1[0].tooltips.append(
            ('Sunshine duration', '@so{int} min per 10 min'))
        hover_p1[0].tooltips.append(
            ('Cumulated sunshine duration', '@ssd_cum{f0.0} h'))

    # temperature
    h_line = p1.line(x='time',
                     y='tl',
                     source=df,
                     line_width=4,
                     color=tcol,
                     legend='Temperature')
    p1.yaxis[0].axis_label = 'Temperature (°C)'
    p1.yaxis[0].major_label_text_color = tcol
    p1.yaxis[0].axis_label_text_color = tcol
    p1.yaxis[0].minor_tick_line_color = tcol
    p1.yaxis[0].major_tick_line_color = tcol
    p1.yaxis[0].axis_line_color = tcol
    p1.yaxis[0].axis_label_text_font_style = "normal"

    # dew point
    if 'tp' in df.columns:
        p1.y_range = Range1d(df['tp'].min() - 2, df['tl'].max() + 2)
        p1.line(x='time',
                y='tp',
                source=df,
                line_width=4,
                color=hcol,
                legend='Dewpoint')
    else:
        # relative humidity
        p1.y_range = Range1d(df['tl'].min() - 2, df['tl'].max() + 2)
        p1.extra_y_ranges = {'rf': Range1d(start=0, end=100)}
        p1.add_layout(LinearAxis(y_range_name='rf'), 'right')
        p1.line(x='time',
                y='rf',
                source=df,
                line_width=4,
                color=hcol,
                legend='Relative Humidity',
                y_range_name='rf')
        p1.yaxis[1].axis_label = 'Relative humidity (%)'
        p1.yaxis[1].major_label_text_color = hcol
        p1.yaxis[1].axis_label_text_color = hcol
        p1.yaxis[1].minor_tick_line_color = hcol
        p1.yaxis[1].major_tick_line_color = hcol
        p1.yaxis[1].axis_line_color = hcol

    # precipitation (3 h sums)
    if 'rrsum' in df.columns:
        if df['rrsum'].sum(
        ) > 0:  #axis would disappear when there was no rain measured
            p1.extra_y_ranges['rrsum'] = Range1d(start=0,
                                                 end=(df['rrsum'].max() * 2))
        else:
            p1.extra_y_ranges['rrsum'] = Range1d(start=0, end=10)
        p1.add_layout(LinearAxis(y_range_name='rrsum'), 'right')

        timeoffset = 0  # timeoffset: dodge to correctly bin bar in time
        if rrsum_period > 10: timeoffset = -60 * rrsum_period / 2 * 1000
        rr = p1.vbar(x=dodge('time', timeoffset, range=p1.x_range),
                     top='rrsum',
                     width=get_width() * rrsum_period / 10,
                     source=df,
                     fill_color=pcol,
                     line_alpha=0,
                     line_width=0,
                     fill_alpha=0.5,
                     legend='Precipitation',
                     y_range_name='rrsum')
        rr.level = 'underlay'
        if rrsum_period >= 60:
            rr_period = str(round_dec(rrsum_period / 60, decimals=1)) + ' h'
        else:
            rr_period = str(rrsum_period) + ' min'
        hover_p1[0].tooltips.append(
            ('Precipitation', '@rrsumm{f0.0} mm in ' + rr_period))
        hover_p1[0].tooltips.append(
            ('Cumulated precipitation', '@rr_cum{f0.0} mm'))

        p1.yaxis[2].major_label_text_color = pcol
        p1.yaxis[2].axis_label_text_color = pcol
        p1.yaxis[2].minor_tick_line_color = pcol
        p1.yaxis[2].major_tick_line_color = pcol
        p1.yaxis[2].axis_line_color = pcol
        p1.yaxis[2].axis_label = 'Precipitation (mm)'

    # hover
    hover_p1.formatters = {"time": "datetime"}
    hover_p1.mode = 'vline'
    hover_p1.renderers = [h_line]  #### to fix if missing value

    # legend
    p1.legend.location = (0, 15)  # above plot
    p1.legend.orientation = 'horizontal'
    p1.legend.click_policy = "hide"
    p1.legend.label_text_font_size = font_size_legend
    p1.add_layout(p1.legend[0], 'above')

    # font style
    p1 = set_font_style_axis(p1)

    return p1