def plot_happiness(self, figsize=(600, 300), colors=['darkgreen', 'darksalmon', 'darkred', 'gold']): df = self.happiness df['Dates'] = pd.to_datetime(df['Dates']) df.index = df['Dates'] p = bkh.figure(x_axis_type='datetime', plot_width=figsize[0], plot_height=figsize[1]) p.xaxis[0].formatter = bkm.DatetimeTickFormatter(days=['%d/%m']) p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Survey Response 0-10 ("Not at all"-"Completely")' for i, s in enumerate([ 'Life satisfaction', 'Feeling worthwhile', 'Happiness', 'Anxiety' ]): p.line(x=df.index.values, y=df[s].values, color=colors[0], legend_label=s, line_color=colors[i]) p.legend.location = 'center_right' bkh.show(p)
def plot_demand_discrepancy_bkh(self, figsize=(600, 300), plot_confidence=True): p = bkh.figure(plot_width=figsize[0], plot_height=figsize[1], x_axis_type='datetime') if plot_confidence: p.varea(x=self.grid_average.DATE[self.COVID_CUTOFF:], y1=(self.Y_COVID.flatten() / (self.Y_COVID_PREDICT_mean.flatten() + self.Y_COVID_PREDICT_conf.flatten())).flatten(), y2=(self.Y_COVID.flatten() / (self.Y_COVID_PREDICT_mean.flatten() - self.Y_COVID_PREDICT_conf.flatten())).flatten(), alpha=0.2, legend_label='Confidence') p.line(x=self.grid_average.DATE[self.COVID_CUTOFF:], y=np.ones(len(self.grid_average.DATE[self.COVID_CUTOFF:])), line_dash='dashed', color='black') p.line(x=self.grid_average.DATE[self.COVID_CUTOFF:], y=self.Y_COVID.flatten() / self.Y_COVID_PREDICT_mean.flatten(), legend_label='Mean') p.xaxis.axis_label = 'Date' p.xaxis[0].formatter = bkm.DatetimeTickFormatter(days=['%d/%m']) p.yaxis.axis_label = 'Net Demand (True) / Net Demand (Expected)' #bkh.output_notebook() bkh.show(p)
def plot_domestic_issues(self, figsize=(600, 300), plot_bounds=True, colors=['black', 'darkturquoise']): df = self.wellness df['Date'] = pd.to_datetime(df['Date']) df.index = df['Date'] p = bkh.figure(x_axis_type='datetime', plot_width=figsize[0], plot_height=figsize[1]) p.xaxis[0].formatter = bkm.DatetimeTickFormatter(days=['%d/%m']) p.xaxis.axis_label = 'Date' p.yaxis.axis_label = '% of actions delivered above normal levels' df['avg'] = df.mean(axis=1) p.line(x=df.index.values, y=df['avg'].values, color=colors[0], legend_label="Mean action on domestic issues") if plot_bounds: df['min'] = df.min(axis=1) df['max'] = df.max(axis=1) p.varea(x=df.index.values, y1=df['min'].values, y2=df['max'].values, alpha=0.2, color=colors[1], legend_label='Max/min bounds') bkh.show(p)
def new_plot(self, title, units, *, line_width=None, precision=2): """ Creates a blank line plot for with timestamps on the x-axis and a line for each data series on the y-axis. """ plot = plotting.figure(title=title, tools=[]) self.active_plot = plot self.plots.append(plot) self.colors = list(colors) self.units = units self.line_width = line_width or self.line_width plot.plot_width = self.width plot.plot_height = self.height plot.x_range = self.x_range datetime_tick_formats = { key: ["%a %b %d %H:%M:%S"] for key in ("seconds", "minsec", "minutes", "hourmin", "hours", "days") } plot.xaxis.formatter = models.DatetimeTickFormatter(**datetime_tick_formats) # https://bokeh.pydata.org/en/latest/docs/reference/models/formatters.html # plot.yaxis.formatter = models.NumeralTickFormatter(format="0a") plot.yaxis.formatter = models.NumeralTickFormatter(format="0,0.00 a") # With default precision level 2 (decimal places) # The units_formats = "@y{0,0.00}" # and the value would look like 1,234,567.89 units_formats = f"@y{{0,0.{'0' * precision}}}" hover = models.HoverTool( # mode = vline would be nice to use, # but then separate hovers block each when lines are too close. # Would like a single hover box with time once, and a value per line # perhaps this will help acheive that: # https://stackoverflow.com/questions/29435200/bokeh-plotting-enable-tooltips-for-only-some-glyphs mode="mouse", # other optins: vline line_policy="nearest", # other optins: prev, next, nearest, interp, none tooltips=[ ("Name", "$name"), ("Time", "@x{%a %m/%d %H:%M:%S}"), (self.units, units_formats), ], formatters={"x": "datetime", "Time": "datetime", "@x": "datetime"}, ) plot.add_tools(hover) plot.add_tools(models.BoxZoomTool()) plot.add_tools(models.HelpTool()) plot.add_tools(models.PanTool()) plot.add_tools(models.WheelZoomTool(dimensions="width")) plot.toolbar.active_scroll = plot.select_one(models.WheelZoomTool) plot.add_tools(models.WheelZoomTool(dimensions="height")) plot.add_tools(models.UndoTool()) plot.add_tools(models.RedoTool()) plot.add_tools(models.ResetTool()) plot.add_tools(models.SaveTool())
def create_plot(self, counties): filename = self.create_filename() bp.output_file(filename, title=self.title) p = bp.figure(title=self.title, x_axis_type="datetime", width=1200, height=700) legend_items = [] for a, b in counties: if self.dublin == False and a == "Dublin": continue temp = b.copy() temp['StrDate'] = temp['TimeStamp'].apply( lambda x: x.strftime("%a, %b %d")) source = bp.ColumnDataSource(temp) leg = p.line("TimeStamp", self.metric, source=source, line_width=2, line_color=self.counties[a]['color'], line_dash=self.counties[a]['dash']) legend_items.append((a, [leg])) legend = bm.Legend(items=legend_items, location='top_right', orientation='vertical', border_line_color="black") p.add_layout(legend, 'right') p.legend.click_policy = "hide" p.legend.label_text_font_size = '12px' p.legend.label_text_font = 'Helvetica' p.legend.location = "top_left" p.legend.background_fill_color = 'slategray' p.legend.background_fill_alpha = 0.5 tools = bm.HoverTool( tooltips=[("Date", "@StrDate"), ( "County", "@CountyName"), ("Cases", "@ConfirmedCovidCases{0, 0}")]) p.add_tools(tools) p.title.text_font = "Helvetica" p.title.text_font_size = "18px" p.background_fill_color = 'slategray' p.background_fill_alpha = 0.5 p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"], days=["%b, %d"], hours=["%H:%M"]) bp.show(p)
def make_timeseries_plot() -> plotting.Figure: """Make an empty timeseries plot with all my customizations.""" plot = plotting.figure(plot_width=900, plot_height=400, x_axis_type="datetime") plot.toolbar.active_drag = None plot.toolbar.active_scroll = None plot.toolbar.active_tap = None plot.toolbar.logo = None plot.toolbar_location = None plot.xaxis.formatter = models.DatetimeTickFormatter( hours=["%a %I%p"], days=["%a %I%p"] ) return plot
def plot_daily_gas_bkh(self, figsize=(650, 450), plot_temperature=False, colors=['black', 'darkturquoise']): p = bkh.figure(x_axis_type='datetime', plot_width=figsize[0], plot_height=figsize[1]) p.line(x=self.energy_average['Date_'], y=32 * np.ones(len(self.energy_average)), line_dash='dashed', line_color=colors[0], legend_label='Typical domestic use (medium)') p.line(x=self.energy_average['Date_'], y=self.energy_average['gas_daily_total'], line_color=colors[0], legend_label='Mean of 115,000 UK households') p.xaxis.axis_label = 'Date' p.xaxis[0].formatter = bkm.DatetimeTickFormatter(days=['%d/%m']) p.y_range = bkm.Range1d(15, 70) p.yaxis.axis_label = 'Gas Consumption (Corrected) (kWh/ALP)' p.yaxis.axis_label_text_color = colors[0] if plot_temperature and self.weather_file: p.extra_y_ranges = {'temperature': bkm.Range1d(start=6, end=24)} p.line(x=self.energy_average['Date_'], y=self.energy_average['temperature'], line_color=colors[1], legend_label='Temperature', y_range_name='temperature') p.add_layout( bkm.LinearAxis(y_range_name='temperature', axis_label='Mean Temperature (°C)', axis_label_text_color=colors[1], axis_line_color=colors[1], major_label_text_color=colors[1], major_tick_line_color=colors[1], minor_tick_line_color=colors[1]), 'right') r = self.energy_average[['gas_daily_total', 'temperature' ]].corr(method='pearson').values[1, 0] p.legend.title = f'R = {r:.3f}' p.legend.location = 'top_left' p.legend.background_fill_alpha = 1.0 #bkh.output_notebook() bkh.show(p)
def create_plot(self): plot = bokeh_plotting.figure( width=1000, height=500, title='Files per {} minutes'.format(self.interval), x_axis_label='Time (UTC)', x_axis_type='datetime', y_axis_label='Fileprocesslog Count', ) plot.add_tools(self.hover) plot.xaxis.formatter = bokeh_models.DatetimeTickFormatter( minutes=["%H:%M"], hours=["%H:%M"], days=["%Y-%m-%d"], ) plot.xaxis.major_label_orientation = pi / 4 return plot
def create_plot(self, data): filename = self.create_filename() bp.output_file(filename, title=self.title) p = bp.figure(title=self.title, x_axis_type="datetime", width=1200, height=700) temp = data.copy() temp['StrDate'] = temp['TimeStamp'].apply( lambda x: x.strftime("%a, %b %d")) temp['Base'] = 0 source = bp.ColumnDataSource(temp) p.varea("TimeStamp", "Daily", "Base", source=source, fill_color="pink", fill_alpha=0.5, legend_label="Daily Cases") p.line("TimeStamp", "Average", source=source, line_width=3, line_color="crimson", legend_label="Average Daily Cases") tools = bm.HoverTool(tooltips=[("Date", "@StrDate"), ("Daily Cases", "@Daily{0, 0}"), ("Average Cases", "@Average{0, 0}")], mode="vline") p.add_tools(tools) p.legend.location = "top_left" p.legend.click_policy = "hide" p.title.text_font = "Helvetica" p.title.text_font_size = "18px" p.background_fill_color = 'slategray' # p.background_fill_alpha = 0.25 p.xaxis.formatter = bm.DatetimeTickFormatter(months=["%b, %Y"], days=["%b, %d"], hours=["%H:%M"]) bp.show(p)
def plot_timeline_bkh(self, figsize=(600, 300)): p = bkh.figure(x_axis_type='datetime', plot_width=figsize[0], plot_height=figsize[1]) p.line(x=self.energy['Date'], y=self.energy['Electricity'], color='royalblue', legend_label='Electricity') p.line(x=self.energy['Date'], y=self.energy['Gas (corrected)'], color='orange', legend_label='Gas (corrected)') p.yaxis.axis_label = 'kWh' p.xaxis.axis_label = 'Date' p.xaxis[0].formatter = bkm.DatetimeTickFormatter(days=['%d/%m']) #bkh.output_notebook() bkh.show(p)
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)
def style_figure(fig, legend_loc): fig.xaxis.formatter = bo_mo.DatetimeTickFormatter(days="%d/%m/%y") fig.legend.location = legend_loc fig.legend.click_policy = "hide" return fig
# Fill with the data so far. for line in temperature_file: line = line.strip().split(',') date, temp = line date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S") temp = float(temp) new_line = {'time': [date], 'temp': [temp]} data.stream(new_line, rollover=100) # Here, we make the figure and add the line glyph p = bkp.figure(title='Streaming Data Demo', plot_width=1600, plot_height=450, x_axis_type='datetime') p.line(x='time', y='temp', source=data) # Make pretty axes p.xaxis.formatter = bkm.DatetimeTickFormatter( hours=["%d %B %Y"], days=["%d %B %Y"], months=["%d %B %Y"], years=["%d %B %Y"], ) p.xaxis.axis_label = 'Time' p.yaxis.axis_label = 'Temperature' # Add the figure, and the periodic callback. bkp.curdoc().add_root(p) bkp.curdoc().add_periodic_callback(monitor_file, 50)
def make_power_graph(output_file: str, data: typ.List, window: int) -> None: """グラフ作成. Args: output_file: 出力ファイル名 data: データ window: 移動平均のサンプル数 """ cols: typ.Tuple = ("time", "電力量", "電力", "電流R", "電流T", "MA電力", "MA電流R", "MA電流T") datadict: typ.Dict = {} for col in cols: datadict[col] = [] has_data: bool = len(data) > 0 for row in data: datadict["time"].append(row["created_at"]) datadict["電力量"].append(calc_電力量(row)) datadict["電力"].append(row["瞬時電力"]) datadict["電流R"].append(row["瞬時電流_r"] / 10.0) datadict["電流T"].append(row["瞬時電流_t"] / 10.0) datadict["MA電力"].append(statistics.mean(datadict["電力"][-window:])) datadict["MA電流T"].append(statistics.mean(datadict["電流T"][-window:])) datadict["MA電流R"].append(statistics.mean(datadict["電流R"][-window:])) source: bp.ColumnDataSource = bp.ColumnDataSource(datadict) tooltips: typ.List[typ.Tuple[str, str]] = [ ("time", "@time{%F %T}"), ("積算電力量", "@{電力量}{0,0.0}"), ("瞬時電力", "@{電力}{0,0}"), ("瞬時電流(R相)", "@{電流R}{0,0.0}"), ("瞬時電流(T相)", "@{電流T}{0,0.0}"), ] hover_tool: bm.HoverTool = bm.HoverTool(tooltips=tooltips, formatters={"@time": "datetime"}) bp.output_file(output_file, title="Power consumption") fig: bp.figure = bp.figure( title="Power consumption", x_axis_type="datetime", x_axis_label="時刻", y_axis_label="電力量[kWh]", sizing_mode="stretch_both", ) fig.add_tools(hover_tool) fmt: typ.List[str] = ["%H:%M"] fig.xaxis.formatter = bm.DatetimeTickFormatter(hours=fmt, hourmin=fmt, minutes=fmt) if has_data: 電力量_min: float = min(datadict["電力量"]) 電力量_max: float = max(datadict["電力量"]) 電力量_5p: float = (電力量_max - 電力量_min) * 0.05 fig.y_range = bm.Range1d(電力量_min - 電力量_5p, 電力量_max + 電力量_5p) fig.extra_y_ranges["W"] = bm.Range1d( 0, max(datadict["電力"]) * 1.05 if has_data else 0) fig.add_layout(bm.LinearAxis(y_range_name="W", axis_label="電力[W]"), "left") fig.extra_y_ranges["A"] = bm.Range1d( 0, max(*datadict["電流R"], *datadict["電流T"]) * 1.05 if has_data else 0) fig.add_layout(bm.LinearAxis(y_range_name="A", axis_label="電流[A]"), "right") fig.line("time", "電力量", legend_label="積算電力量", line_color="red", source=source) raw_data: typ.List = [ ("電力", "W", "瞬時電力", "orange"), ("電流R", "A", "瞬時電流(R相)", "blue"), ("電流T", "A", "瞬時電流(T相)", "green"), ] for col, range_name, legend_label, color in raw_data: fig.line( "time", col, y_range_name=range_name, legend_label=legend_label, line_color=color, line_alpha=0.8, source=source, ).visible = False ma_data: typ.List = [ ("MA電力", "W", "瞬時電力(移動平均)", "orange"), ("MA電流R", "A", "瞬時電流(R相)(移動平均)", "blue"), ("MA電流T", "A", "瞬時電流(T相)(移動平均)", "green"), ] for col, range_name, legend_label, color in ma_data: fig.line( "time", col, y_range_name=range_name, legend_label=legend_label, line_color=color, line_width=2, line_alpha=0.8, line_dash="dotted", source=source, ) fig.legend.click_policy = "hide" fig.legend.location = "top_left" bp.save(fig)
def make_temp_graph(output_file: str, temp_data: typ.List, co2_data: typ.List, bme280_data: typ.List) -> None: """グラフ作成. Args: output_file: 出力ファイル名 temp_data: 温度データ co2_data: CO2データ bme280_data: BME280のデータ """ tooltips: typ.List[typ.Tuple[str, str]] = [ ("time", "@time{%F %T}"), ] df: pd.DataFrame deg_max: int = 0 num_data: int = 0 y_axis_label: str = "温度[℃]" if len(temp_data) > 0: num_data += 1 if len(co2_data) > 0: num_data += 1 if len(bme280_data) > 0: num_data += 1 if len(temp_data) > 0: df1: pd.DataFrame = pd.DataFrame(temp_data, columns=list(temp_data[0].keys())) df1 = df1.rename(columns={"created_at": "time"}) if num_data > 1: df1["time"] = df1["time"].apply( lambda x: x.replace(second=0, microsecond=0)) df1["temp"] /= 1000 df1 = df1[["time", "temp"]].drop_duplicates(subset="time") df = df1 tooltips.append(("CPU温度", "@temp{0.0}")) deg_max = int(df["temp"].max()) + 10 if len(co2_data) > 0: df2: pd.DataFrame = pd.DataFrame(co2_data, columns=list(co2_data[0].keys())) df2 = df2.rename(columns={"temp": "temp2", "created_at": "time"}) if num_data > 1: df2["time"] = df2["time"].apply( lambda x: x.replace(second=0, microsecond=0)) df2 = df2[["time", "co2", "temp2"]].drop_duplicates(subset="time") if len(temp_data) > 0: df = pd.merge(df1, df2, on="time", how="outer").sort_values("time") else: df = df2 if len(bme280_data) == 0: tooltips.append(("気温", "@temp2")) tooltips.append(("CO₂", "@co2")) deg_max = max(deg_max, int(df["temp2"].max()) + 10) if len(bme280_data) > 0: df3: pd.DataFrame = pd.DataFrame(bme280_data, columns=list(bme280_data[0].keys())) df3 = df3.rename(columns={"temp": "temp3", "created_at": "time"}) if num_data > 1: df3["time"] = df3["time"].apply( lambda x: x.replace(second=0, microsecond=0)) df3 = df3[["time", "temp3", "pressure", "humidity"]].drop_duplicates(subset="time") if num_data > 1: df = pd.merge(df, df3, on="time", how="outer").sort_values("time") else: df = df3 tooltips.append(("気温", "@temp3{0.0}")) tooltips.append(("湿度", "@humidity{0.0}")) tooltips.append(("気圧", "@pressure{0,0.0}")) deg_max = max(deg_max, int(df["temp3"].max()) + 10, int(df["humidity"].max()) + 10) y_axis_label += "/湿度[%]" source: bp.ColumnDataSource = bp.ColumnDataSource(df) hover_tool: bm.HoverTool = bm.HoverTool(tooltips=tooltips, formatters={"@time": "datetime"}) bp.output_file(output_file, title="Temperature") fig: bp.figure = bp.figure( title="Temperature", x_axis_type="datetime", x_axis_label="時刻", y_axis_label=y_axis_label, sizing_mode="stretch_both", ) fig.add_tools(hover_tool) fmt: typ.List[str] = ["%H:%M"] fig.xaxis.formatter = bm.DatetimeTickFormatter(hours=fmt, hourmin=fmt, minutes=fmt) fig.y_range = bm.Range1d(0, deg_max) if len(temp_data) > 0: fig.line("time", "temp", legend_label="CPU温度", line_color="red", source=source) if len(co2_data) > 0: if len(bme280_data) == 0: fig.line("time", "temp2", legend_label="気温", line_color="darkorange", source=source) fig.extra_y_ranges["ppm"] = bm.Range1d( 0, max(2000, df["co2"].max() * 1.05)) fig.add_layout(bm.LinearAxis(y_range_name="ppm", axis_label="濃度[ppm]"), "right") fig.line("time", "co2", legend_label="CO₂", line_color="green", y_range_name="ppm", source=source) if len(bme280_data) > 0: fig.line("time", "temp3", legend_label="気温", line_color="darkorange", source=source) fig.line("time", "humidity", legend_label="湿度", line_color="blue", source=source) fig.extra_y_ranges["pressure"] = bm.Range1d( min(990, df["pressure"].min()), max(1020, df["pressure"].max())) fig.add_layout( bm.LinearAxis(y_range_name="pressure", axis_label="気圧[hPa]"), "right") fig.line("time", "pressure", legend_label="気圧", line_color="deeppink", y_range_name="pressure", source=source) fig.legend.click_policy = "hide" fig.legend.location = "top_left" bp.save(fig)
def plot_all(self) -> plotting.Figure: """Creates plot containing all transations and balance over time. The plot will contain a line showing the balance over time, with scatter points to show the absolute value of each transation. Returns ------- plotting.Figure Figure object with all midata transactions plotted. """ balance_hover = models.HoverTool( names=["balance"], toggleable=False, tooltips=[ ("Date", "@date{%d/%m/%Y}"), ("Balance (£)", "@balance{0,0.00}"), ], formatters={"@date": "datetime"}, ) amount_hover = models.HoverTool( names=["abs_amount"], toggleable=False, tooltips=[ ("Date", "@date{%d/%m/%Y}"), ("Transaction (£)", "@amount{+0,0.00}"), ("Balance (£)", "@balance{+0,0.00}"), ("Merchant / Description", "@description"), ], formatters={"@date": "datetime"}, ) p = plotting.figure( title="All transactions", x_axis_label="Date", y_axis_label="Amount (£)", sizing_mode="stretch_both", tools=[ "pan", "box_select", "xwheel_zoom", "reset", "save", balance_hover, amount_hover, ], ) p.xaxis[0].formatter = models.DatetimeTickFormatter() p.y_range = models.DataRange1d(bounds=(0, 10000)) epoch = dt.datetime.utcfromtimestamp(0) max_date = (dt.datetime.today() - epoch).total_seconds() min_date = max_date - (2 * 365 * 24 * 60 * 60) p.x_range = models.DataRange1d(bounds=(min_date * 1000, max_date * 1000)) p.line( x="date", y="balance", source=self.source, legend_label="Balance", name="balance", line_width=2, ) p.scatter( "date", "abs_amount", size=5, color="colour", name="abs_amount", source=self.source, legend_label="Absolute Transaction", fill_alpha=0.8, ) p.legend.click_policy = "hide" return p