Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Bokeh plot demo #9423

Merged
merged 4 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion demo/outbreak_forecast/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@ matplotlib
bokeh
plotly
altair
opencv-python
2 changes: 1 addition & 1 deletion demo/outbreak_forecast/run.ipynb
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: outbreak_forecast\n", "### Generate a plot based on 5 inputs.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy matplotlib bokeh plotly altair opencv-python"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import altair\n", "\n", "import gradio as gr\n", "from math import sqrt\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import plotly.express as px\n", "import pandas as pd\n", "\n", "def outbreak(plot_type, r, month, countries, social_distancing):\n", " months = [\"January\", \"February\", \"March\", \"April\", \"May\"]\n", " m = months.index(month)\n", " start_day = 30 * m\n", " final_day = 30 * (m + 1)\n", " x = np.arange(start_day, final_day + 1)\n", " pop_count = {\"USA\": 350, \"Canada\": 40, \"Mexico\": 300, \"UK\": 120}\n", " if social_distancing:\n", " r = sqrt(r)\n", " df = pd.DataFrame({\"day\": x})\n", " for country in countries:\n", " df[country] = x ** (r) * (pop_count[country] + 1)\n", "\n", " if plot_type == \"Matplotlib\":\n", " fig = plt.figure()\n", " plt.plot(df[\"day\"], df[countries].to_numpy())\n", " plt.title(\"Outbreak in \" + month)\n", " plt.ylabel(\"Cases\")\n", " plt.xlabel(\"Days since Day 0\")\n", " plt.legend(countries)\n", " return fig\n", " elif plot_type == \"Plotly\":\n", " fig = px.line(df, x=\"day\", y=countries)\n", " fig.update_layout(\n", " title=\"Outbreak in \" + month,\n", " xaxis_title=\"Cases\",\n", " yaxis_title=\"Days Since Day 0\",\n", " )\n", " return fig\n", " elif plot_type == \"Altair\":\n", " df = df.melt(id_vars=\"day\").rename(columns={\"variable\": \"country\"})\n", " fig = altair.Chart(df).mark_line().encode(x=\"day\", y=\"value\", color=\"country\")\n", " return fig\n", " else:\n", " raise ValueError(\"A plot type must be selected\")\n", "\n", "inputs = [\n", " gr.Dropdown([\"Matplotlib\", \"Plotly\", \"Altair\"], label=\"Plot Type\"),\n", " gr.Slider(1, 4, 3.2, label=\"R\"),\n", " gr.Dropdown([\"January\", \"February\", \"March\", \"April\", \"May\"], label=\"Month\"),\n", " gr.CheckboxGroup(\n", " [\"USA\", \"Canada\", \"Mexico\", \"UK\"], label=\"Countries\", value=[\"USA\", \"Canada\"]\n", " ),\n", " gr.Checkbox(label=\"Social Distancing?\"),\n", "]\n", "outputs = gr.Plot()\n", "\n", "demo = gr.Interface(\n", " fn=outbreak,\n", " inputs=inputs,\n", " outputs=outputs,\n", " examples=[\n", " [\"Matplotlib\", 2, \"March\", [\"Mexico\", \"UK\"], True],\n", " [\"Altair\", 2, \"March\", [\"Mexico\", \"Canada\"], True],\n", " [\"Plotly\", 3.6, \"February\", [\"Canada\", \"Mexico\", \"UK\"], False],\n", " ],\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: outbreak_forecast\n", "### Generate a plot based on 5 inputs.\n", " "]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio numpy matplotlib bokeh plotly altair "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from math import sqrt\n", "import numpy as np\n", "import pandas as pd\n", "\n", "def outbreak(plot_type, r, month, countries, social_distancing):\n", " months = [\"January\", \"February\", \"March\", \"April\", \"May\"]\n", " m = months.index(month)\n", " start_day = 30 * m\n", " final_day = 30 * (m + 1)\n", " x = np.arange(start_day, final_day + 1)\n", " pop_count = {\"USA\": 350, \"Canada\": 40, \"Mexico\": 300, \"UK\": 120}\n", " if social_distancing:\n", " r = sqrt(r)\n", " df = pd.DataFrame({\"day\": x})\n", " for country in countries:\n", " df[country] = x ** (r) * (pop_count[country] + 1)\n", "\n", " if plot_type == \"Matplotlib\":\n", " import matplotlib.pyplot as plt\n", "\n", " fig = plt.figure()\n", " plt.plot(df[\"day\"], df[countries].to_numpy())\n", " plt.title(\"Outbreak in \" + month)\n", " plt.ylabel(\"Cases\")\n", " plt.xlabel(\"Days since Day 0\")\n", " plt.legend(countries)\n", " return fig\n", " elif plot_type == \"Plotly\":\n", " import plotly.express as px\n", "\n", " fig = px.line(df, x=\"day\", y=countries)\n", " fig.update_layout(\n", " title=\"Outbreak in \" + month,\n", " xaxis_title=\"Cases\",\n", " yaxis_title=\"Days Since Day 0\",\n", " )\n", " return fig\n", " elif plot_type == \"Altair\":\n", " import altair\n", "\n", " df = df.melt(id_vars=\"day\").rename(columns={\"variable\": \"country\"})\n", " fig = altair.Chart(df).mark_line().encode(x=\"day\", y=\"value\", color=\"country\")\n", " return fig\n", " elif plot_type == \"Bokeh\":\n", " from bokeh.plotting import figure\n", " from bokeh.models import ColumnDataSource\n", "\n", " source = ColumnDataSource(df)\n", " fig = figure(title=\"Outbreak in \" + month, x_axis_label=\"Days since Day 0\", y_axis_label=\"Cases\")\n", " for country in countries:\n", " fig.line(\"day\", country, source=source, legend_label=country)\n", " return fig\n", " else:\n", " raise ValueError(\"A plot type must be selected\")\n", "\n", "inputs = [\n", " gr.Dropdown([\"Matplotlib\", \"Plotly\", \"Altair\", \"Bokeh\"], label=\"Plot Type\", value=\"Matplotlib\"),\n", " gr.Slider(1, 4, 3.2, label=\"R\"),\n", " gr.Dropdown([\"January\", \"February\", \"March\", \"April\", \"May\"], label=\"Month\", value=\"March\"),\n", " gr.CheckboxGroup(\n", " [\"USA\", \"Canada\", \"Mexico\", \"UK\"], label=\"Countries\", value=[\"USA\", \"Canada\"]\n", " ),\n", " gr.Checkbox(label=\"Social Distancing?\"),\n", "]\n", "outputs = gr.Plot()\n", "\n", "demo = gr.Interface(\n", " fn=outbreak,\n", " inputs=inputs,\n", " outputs=outputs,\n", " examples=[\n", " [\"Matplotlib\", 2, \"March\", [\"Mexico\", \"UK\"], True],\n", " [\"Altair\", 2, \"March\", [\"Mexico\", \"Canada\"], True],\n", " [\"Plotly\", 3.6, \"February\", [\"Canada\", \"Mexico\", \"UK\"], False],\n", " [\"Bokeh\", 3.2, \"April\", [\"Canada\", \"UK\"], False],\n", " ],\n", " cache_examples=True,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
24 changes: 18 additions & 6 deletions demo/outbreak_forecast/run.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import altair

import gradio as gr
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
import plotly.express as px
import pandas as pd

def outbreak(plot_type, r, month, countries, social_distancing):
Expand All @@ -21,6 +17,8 @@ def outbreak(plot_type, r, month, countries, social_distancing):
df[country] = x ** (r) * (pop_count[country] + 1)

if plot_type == "Matplotlib":
import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(df["day"], df[countries].to_numpy())
plt.title("Outbreak in " + month)
Expand All @@ -29,6 +27,8 @@ def outbreak(plot_type, r, month, countries, social_distancing):
plt.legend(countries)
return fig
elif plot_type == "Plotly":
import plotly.express as px

fig = px.line(df, x="day", y=countries)
fig.update_layout(
title="Outbreak in " + month,
Expand All @@ -37,16 +37,27 @@ def outbreak(plot_type, r, month, countries, social_distancing):
)
return fig
elif plot_type == "Altair":
import altair

df = df.melt(id_vars="day").rename(columns={"variable": "country"})
fig = altair.Chart(df).mark_line().encode(x="day", y="value", color="country")
return fig
elif plot_type == "Bokeh":
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

source = ColumnDataSource(df)
fig = figure(title="Outbreak in " + month, x_axis_label="Days since Day 0", y_axis_label="Cases")
for country in countries:
fig.line("day", country, source=source, legend_label=country)
return fig
else:
raise ValueError("A plot type must be selected")

inputs = [
gr.Dropdown(["Matplotlib", "Plotly", "Altair"], label="Plot Type"),
gr.Dropdown(["Matplotlib", "Plotly", "Altair", "Bokeh"], label="Plot Type", value="Matplotlib"),
gr.Slider(1, 4, 3.2, label="R"),
gr.Dropdown(["January", "February", "March", "April", "May"], label="Month"),
gr.Dropdown(["January", "February", "March", "April", "May"], label="Month", value="March"),
gr.CheckboxGroup(
["USA", "Canada", "Mexico", "UK"], label="Countries", value=["USA", "Canada"]
),
Expand All @@ -62,6 +73,7 @@ def outbreak(plot_type, r, month, countries, social_distancing):
["Matplotlib", 2, "March", ["Mexico", "UK"], True],
["Altair", 2, "March", ["Mexico", "Canada"], True],
["Plotly", 3.6, "February", ["Canada", "Mexico", "UK"], False],
["Bokeh", 3.2, "April", ["Canada", "UK"], False],
],
cache_examples=True,
)
Expand Down
28 changes: 27 additions & 1 deletion js/spa/test/outbreak_forecast.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,25 @@ test("selecting altair should show altair plot and pressing clear should clear o
await expect(altair).toHaveCount(0);
});

test("switching between all 3 plot types and pressing submit should update output component to corresponding plot type", async ({
test("selecting bokeh should show bokeh plot and pressing clear should clear output", async ({
page
}) => {
await page.getByLabel("Plot Type").click();
await page.getByRole("option", { name: "bokeh" }).click();
await page.getByLabel("Month").click();
await page.getByRole("option", { name: "January" }).click();
await page.getByLabel("Social Distancing?").check();

await page.click("text=Submit");

const altair = await page.getByTestId("bokeh");
await expect(altair).toHaveCount(1);

await page.getByRole("button", { name: "Clear" }).click();
await expect(altair).toHaveCount(0);
});

test("switching between all 4 plot types and pressing submit should update output component to corresponding plot type", async ({
page
}) => {
//Matplotlib
Expand Down Expand Up @@ -82,4 +100,12 @@ test("switching between all 3 plot types and pressing submit should update outpu
await page.click("text=Submit");
const altair = await page.getByTestId("altair");
await expect(altair).toHaveCount(1);

//Bokeh
await page.getByLabel("Plot Type").click();
await page.getByRole("option", { name: "Bokeh" }).click();

await page.click("text=Submit");
const bokeh = await page.getByTestId("bokeh");
await expect(bokeh).toHaveCount(1);
});
Loading