def test_basic_lineplot(df_stock): """Test for basic lineplot""" # Create basic lineplot: p_basic_lineplot = df_stock.plot_bokeh(kind="line", show_figure=False) p_basic_lineplot_accessor = df_stock.plot_bokeh.line(show_figure=False) p_basic_lineplot_pandas_backend = df_stock.plot( kind="line", fontsize_title=30, fontsize_label=25, fontsize_ticks=15, fontsize_legend=40, show_figure=False, ) p_basic_lineplot_accessor_pandas_backend = df_stock.plot.line( fontsize_title=30, fontsize_label=25, fontsize_ticks=15, fontsize_legend=40, show_figure=False, ) # Output plot as HTML: output = pandas_bokeh.row([p_basic_lineplot, p_basic_lineplot_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Basic_lineplot.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_pointplot(): "Test for pointplot" x = np.arange(-3, 3, 0.1) y2 = x**2 y3 = x**3 df = pd.DataFrame({"x": x, "Parabula": y2, "Cube": y3}) arguments = dict( x="x", xticks=range(-3, 4), size=5, colormap=["#009933", "#ff3399"], title="Pointplot (Parabula vs. Cube)", marker="x", show_figure=False, ) p_pointplot = df.plot_bokeh(kind="point", **arguments) p_pointplot_accessor = df.plot_bokeh.point(**arguments) p_pointplot_pandas_backend = df.plot(kind="point", **arguments) p_pointplot_accessor_pandas_backend = df.plot.point(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_pointplot, p_pointplot_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Pointplot.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_scatterplot_2(): "Test 2 for scatterplot" # Load Iris Dataset: df = pd.read_csv( r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/iris/iris.csv" ) #Change one value to clearly see the effect of the size keyword df.loc[13, "sepal length (cm)"] = 15 #Make scatterplot: # Create Scatterplot: arguments = dict( x="petal length (cm)", y="sepal width (cm)", category="species", title="Iris DataSet Visualization", size="sepal length (cm)", show_figure=False, ) p_scatter = df.plot_bokeh(kind="scatter", **arguments) p_scatter_accessor = df.plot_bokeh.scatter(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_scatter, p_scatter_accessor]) with open(os.path.join(directory, "Plots", "Scatterplot_2.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_barplot_stacked(): "Test for stacked Barplot" data = { "fruits": ["Apples", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"], "2015": [2, 1, 4, 3, 2, 4], "2016": [5, 3, 3, 2, 4, 6], "2017": [3, 2, 4, 4, 5, 3], } df = pd.DataFrame(data).set_index("fruits") # Make scatterplot: # Create Scatterplot: arguments = dict( ylabel="Price per Unit [€]", title="Fruit prices per Year", stacked=True, alpha=0.6, show_figure=False, ) p_bar = df.plot_bokeh(kind="bar", **arguments) p_bar_accessor = df.plot_bokeh.bar(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_bar, p_bar_accessor]) with open(os.path.join(directory, "Plots", "Barplot_stacked.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_lineplot_with_points(): "Test for lineplot with data points:" # Create complex lineplot: np.random.seed(42) df = pd.DataFrame( {"Google": np.random.randn(1000) + 0.2, "Apple": np.random.randn(1000) + 0.17}, index=pd.date_range("1/1/2000", periods=1000), ) df.index.name = "Date" df = df.cumsum() df = df + 50 arguments = dict( figsize=(600, 450), title="Apple vs Google", xlabel="Date", ylabel="Stock price [$]", yticks=[0, 100, 200, 300, 400], ylim=(100, 200), xlim=("2001-01-01", "2001-02-01"), colormap=["red", "blue"], plot_data_points=True, plot_data_points_size=10, marker="asterisk", show_figure=False, ) p_lineplot_with_points = df.plot_bokeh(kind="line", **arguments) p_lineplot_with_points_accessor = df.plot_bokeh.line(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_lineplot_with_points, p_lineplot_with_points_accessor]) with open(os.path.join(directory, "Plots", "Lineplot_with_points.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_scatterplot_2(df_iris): "Test 2 for scatterplot" # Change one value to clearly see the effect of the size keyword df_iris.loc[13, "sepal length (cm)"] = 15 # Make scatterplot: # Create Scatterplot: arguments = dict( x="petal length (cm)", y="sepal width (cm)", category="species", title="Iris DataSet Visualization", size="sepal length (cm)", show_figure=False, ) p_scatter = df_iris.plot_bokeh(kind="scatter", **arguments) p_scatter_accessor = df_iris.plot_bokeh.scatter(**arguments) p_scatter_pandas_backend = df_iris.plot(kind="scatter", **arguments) p_scatter_accessor_pandas_backend = df_iris.plot.scatter(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_scatter, p_scatter_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Scatterplot_2.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_barplot_stacked(df_fruits): "Test for stacked Barplot" # Create Scatterplot: arguments = dict( ylabel="Price per Unit [€]", title="Fruit prices per Year", stacked=True, alpha=0.6, show_figure=False, ) p_bar = df_fruits.plot_bokeh(kind="bar", **arguments) p_bar_accessor = df_fruits.plot_bokeh.bar(**arguments) p_bar_pandas_backend = df_fruits.plot(kind="bar", **arguments) p_bar_accessor_pandas_backend = df_fruits.plot.bar(**arguments) # Output plot as HTML: output = pandas_bokeh.row([p_bar, p_bar_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Barplot_stacked.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_basic_lineplot_pyspark(spark): """Test for basic lineplot with Pyspark""" # Create basic lineplot: np.random.seed(42) df = pd.DataFrame( { "Google": np.random.randn(1000) + 0.2, "Apple": np.random.randn(1000) + 0.17 }, index=pd.date_range("1/1/2000", periods=1000), ) df.index.name = "Date" df = df.cumsum() df = df + 50 df = spark.createDataFrame(df.reset_index()) p_basic_lineplot = df.plot_bokeh(kind="line", x="Date", show_figure=False) p_basic_lineplot_accessor = df.plot_bokeh.line(x="Date", show_figure=False) # Output plot as HTML: output = pandas_bokeh.row([p_basic_lineplot, p_basic_lineplot_accessor]) with open(os.path.join(directory, "Plots", "Basic_lineplot_PySpark.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_lineplot_with_points(df_stock): "Test for lineplot with data points:" # Create complex lineplot: arguments = dict( figsize=(600, 450), title="Apple vs Google", xlabel="Date", ylabel="Stock price [$]", yticks=[0, 100, 200, 300, 400], ylim=(100, 200), xlim=("2001-01-01", "2001-02-01"), colormap=["red", "blue"], plot_data_points=True, plot_data_points_size=10, marker="asterisk", show_figure=False, ) p_lineplot_with_points = df_stock.plot_bokeh(kind="line", **arguments) p_lineplot_with_points_accessor = df_stock.plot_bokeh.line(**arguments) p_lineplot_with_points_pandas_backend = df_stock.plot(kind="line", **arguments) p_lineplot_with_points_accessor_pandas_backend = df_stock.plot.line( **arguments) # Output plot as HTML: output = pandas_bokeh.row( [p_lineplot_with_points, p_lineplot_with_points_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Lineplot_with_points.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_geolayers_simple(df_states): "Tests for simple geoplot" figure = df_states.plot_bokeh(simplify_shapes=10000, show_figure=False) with open(os.path.join(directory, "Plots", "Geolayers_Simple.html"), "w") as f: f.write(pandas_bokeh.embedded_html(figure)) assert True
def test_hole_geplot(): "Tests for (multi-)polygones with holes." df = gpd.GeoDataFrame.from_file( os.path.join(test_sets_directory, "hole_shapes", "hole_shapes.geojson")) figure = df.plot_bokeh(show_figure=False) with open( os.path.join(directory, "Plots", "Geolayers_Multipolygons_Holes.html"), "w") as f: f.write(pandas_bokeh.embedded_html(figure)) assert True
def test_geolayers_simple(): "Tests for simple" # Read in GeoJSON from URL: df_states = gpd.read_file( r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/states/states.geojson" ) figure = df_states.plot_bokeh(simplify_shapes=10000, show_figure=False) with open( #+ä os.path.join(directory, "Plots", "Geolayers_Simple.html"), "w") as f: f.write(pandas_bokeh.embedded_html(figure)) assert True
def test_complex_lineplot(): """Test for complexd lineplot""" # Create complex lineplot: np.random.seed(42) df = pd.DataFrame( { "Google": np.random.randn(1000) + 0.2, "Apple": np.random.randn(1000) + 0.17 }, index=pd.date_range("1/1/2000", periods=1000), ) df.index.name = "Date" df = df.cumsum() df = df + 50 arguments = dict( figsize=(600, 450), y="Apple", title="Apple vs Google", xlabel="Date", ylabel="Stock price [$]", yticks=[0, 100, 200, 300, 400], ylim=(0, 400), toolbar_location=None, colormap=["red", "blue"], hovertool_string="""<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/170px-Apple_logo_black.svg.png" height="42" alt="@imgs" width="42" style="float: left; margin: 0px 15px 15px 0px;" border="2"></img> Apple <h4> Stock Price: </h4> @{Apple}""", panning=False, zooming=False, show_figure=False, ) p_complex_lineplot = df.plot_bokeh(kind="line", **arguments) p_complex_lineplot_accessor = df.plot_bokeh.line(**arguments) # Output plot as HTML: output = pandas_bokeh.row( [p_complex_lineplot, p_complex_lineplot_accessor]) with open(os.path.join(directory, "Plots", "Complex_lineplot.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_basic_stepplot(df_stock): """Test for basic stepplot""" p_basic_stepplot = df_stock.plot_bokeh(kind="step", show_figure=False) p_basic_stepplot_accessor = df_stock.plot_bokeh.step(show_figure=False) p_basic_stepplot_pandas_backend = df_stock.plot(kind="step", show_figure=False) p_basic_stepplot_accessor_pandas_backend = df_stock.plot.step( show_figure=False) # Output plot as HTML: output = pandas_bokeh.row([p_basic_stepplot, p_basic_stepplot_accessor]) with open(os.path.join(DIRECTORY, "Plots", "Basic_stepplot.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def test_complex_lineplot(df_stock): """Test for complexd lineplot""" # Create complex lineplot: arguments = dict( figsize=(600, 450), y="Apple", title="Apple vs Google", xlabel="Date", ylabel="Stock price [$]", yticks=[0, 100, 200, 300, 400], ylim=(0, 400), toolbar_location=None, colormap=["red", "blue"], hovertool_string="""<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/170px-Apple_logo_black.svg.png" height="42" alt="@imgs" width="42" style="float: left; margin: 0px 15px 15px 0px;" border="2"></img> Apple <h4> Stock Price: </h4> @{Apple}""", panning=False, zooming=False, show_figure=False, ) p_complex_lineplot = df_stock.plot_bokeh(kind="line", **arguments) p_complex_lineplot_accessor = df_stock.plot_bokeh.line(**arguments) p_complex_lineplot_pandas_backend = df_stock.plot(kind="line", **arguments) p_complex_lineplot_accessor_pandas_backend = df_stock.plot.line( **arguments) # Output plot as HTML: output = pandas_bokeh.row([ p_complex_lineplot, p_complex_lineplot_accessor, p_complex_lineplot_pandas_backend, p_complex_lineplot_accessor_pandas_backend, ]) with open(os.path.join(DIRECTORY, "Plots", "Complex_lineplot.html"), "w") as f: f.write(pandas_bokeh.embedded_html(output)) assert True
def embedder(*args, **kwargs): return pandas_bokeh.embedded_html(func(*args, **kwargs))
def get_latest_power_as_plot(asset: Asset, small: bool = False) -> Tuple[str, str]: """Create a plot of an asset's latest power measurement as an embeddable html string (incl. javascript). First returned string is the measurement time, second string is the html string.""" if current_app.config.get("FLEXMEASURES_MODE", "") == "play": before = None # type:ignore else: before = server_now() _, before = convert_query_window_for_demo((before, before)) latest_power = asset.latest_state(event_ends_before=before) if latest_power is not None: latest_power_value = latest_power.value if current_app.config.get("FLEXMEASURES_MODE", "") == "demo": latest_power_datetime = latest_power.datetime.replace( year=datetime.now().year ) else: latest_power_datetime = latest_power.datetime latest_measurement_time_str = localized_datetime_str( latest_power_datetime + asset.event_resolution ) else: latest_power_value = 0 latest_measurement_time_str = "time unknown" if latest_power_value < 0: consumption = True latest_power_value *= -1 else: consumption = False data = { latest_measurement_time_str if not small else "": [0], "Capacity in use": [latest_power_value], "Remaining capacity": [asset.capacity_in_mw - latest_power_value], } percentage_capacity = latest_power_value / asset.capacity_in_mw df = pd.DataFrame(data) p = df.plot_bokeh( kind="bar", x=latest_measurement_time_str if not small else "", y=["Capacity in use", "Remaining capacity"], stacked=True, colormap=[ "%s" % Color( hue=0.3 * min(1.0, 3 / 2 * percentage_capacity), saturation=1, luminance=min(0.5, 1 - percentage_capacity * 3 / 4), ).get_hex_l(), # 0% red, 38% yellow, 67% green, >67% darker green "#f7ebe7", ], alpha=0.7, title=None, xlabel=None, ylabel="Power (%s)" % asset.unit, zooming=False, show_figure=False, hovertool=None, legend=None, toolbar_location=None, figsize=(200, 400) if not small else (100, 100), ylim=(0, asset.capacity_in_mw), xlim=(-0.5, 0.5), ) p.xgrid.visible = False for r in p.renderers: try: r.glyph.width = 1 except AttributeError: pass p.xaxis.ticker = [] p.add_layout( BoxAnnotation(bottom=0, top=asset.capacity_in_mw, fill_color="#f7ebe7") ) plot_html_str = pandas_bokeh.embedded_html(p) hover_tool_str = "%s at %s %s (%s%% capacity).\nLatest state at %s." % ( "Consuming" if consumption else "Running" if latest_power_value == 0 else "Producing", round(latest_power_value, 3), asset.unit, round(100 * percentage_capacity), latest_measurement_time_str, ) return ( latest_measurement_time_str, """<div data-toggle="tooltip" data-placement="bottom" title="%s">%s</div>""" % (hover_tool_str, plot_html_str), )