Updating ui.matplotlib #2892
-
QuestionI'm new to NiceGUI and UIs in general. I thought I'd attempt a minimal data visualisation UI to later explore further possibilities. GOAL: Given a basic sales dataset, the user should be able to explore all data across the various columns (years). Data should be presented as horizontal bar plots, sorted by most sold in descending order, noting that the order may differ across years so this has to be handled accordingly. I unsuccessfully tried to adapt the answer to #55 to update the plot with the new ui.matplotlib, finally managing to get it to work using ui.refreshable. QUESTIONS:
from nicegui import ui
import pandas as pd
@ui.refreshable
def plot_for_selected_year(set_year: str) -> None:
ui.notify(f"Selection: {set_year}")
sorted_data = data.sort_values(by=set_year)
# plot recipe from https://nicegui.io/documentation/matplotlib#matplotlib
with ui.matplotlib(figsize=(19.5, 8.25), tight_layout=True).figure as fig:
fig.patch.set_facecolor('skyblue')
x = sorted_data['Product']
y = sorted_data[set_year]
ax = fig.gca()
ax.barh(x, y, color='magenta')
ax.set_title(f"PRODUCTS SOLD IN {set_year}")
# add values at the end of the horizontal bars
positional_offset = 2.5
for index, value in enumerate(sorted_data[set_year]):
ax.text(value + positional_offset, index, str(value), va='center', fontsize=9)
sales_data = {'Product': ['A', 'B', 'C'],
"2021": [252, 375, 128],
"2022": [311, 422, 322],
"2023": [288, 372, 428],
}
selected_year = "2023" # initial value
data = (pd.DataFrame(sales_data))
with ui.card().classes('bg-black flex flex-col items-center w-[1870px]'):
ui.label("NiceGUI DATA VISUALISER").style('color: magenta; font-size: 200%; font-weight: 800')
ui.separator()
with ui.button_group().props('push glossy'):
# https://nicegui.io/documentation/button_group#button_group_styling
years = ['2021', '2022', '2023']
colours = ['magenta', 'red', 'purple']
for year, colour in zip(years, colours):
ui.button(year, color=colour, on_click=lambda yr=year: plot_for_selected_year.refresh(yr)).props('push')
plot_for_selected_year(selected_year)
ui.run(reload=False, dark=True, title="NiceGUI DATA VISUALISER", window_size=(1920, 1050)) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi @LeoM1970, Here is an example on how to update x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
with ui.matplotlib(figsize=(3, 2)).figure as fig:
fig.gca().plot(x, y, '-')
def update():
with fig:
fig.gca().plot(x, y + 1, ':')
ui.button('Update', on_click=update) The key is to enter the Alternatively you can call x = np.linspace(0.0, 5.0)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plot = ui.matplotlib(figsize=(3, 2))
with plot.figure as fig:
fig.gca().plot(x, y, '-')
def update():
plot.figure.gca().plot(x, y + 1, ':')
plot.update()
ui.button('Update', on_click=update) |
Beta Was this translation helpful? Give feedback.
-
Thank you @falkoschindler for your prompt reply, and to all the team for a great library. |
Beta Was this translation helpful? Give feedback.
Hi @LeoM1970,
Here is an example on how to update
ui.matplotlib
:The key is to enter the
fig
context once again. When leaving this context, the UI element is updated automatically.Alternatively you can call
plot.update()
, but then you need to keep a reference toplot
, e.g. like this: