This commit is contained in:
shao1chuan 2024-03-04 22:22:43 +08:00
parent aea2781f01
commit 2c8b0beb70
20 changed files with 2134 additions and 49 deletions

View File

@ -1,8 +0,0 @@
import plotly.graph_objects as go
from nicegui import ui
fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
ui.plotly(fig).classes('w-full h-40')
ui.run()

View File

@ -0,0 +1,39 @@
from nicegui import ui
columns = [
{'name': 'name', 'label': 'Name', 'field': 'name', 'required': True, 'align': 'left'},
{'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
]
rows = [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol'},
]
ui.table(columns=columns, rows=rows, row_key='name')
# ui.run()
import pandas as pd
from nicegui import ui
df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
ui.aggrid.from_pandas(df).classes('max-h-40')
import plotly.graph_objects as go
from nicegui import ui
from random import random
fig = go.Figure()
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
plot = ui.plotly(fig).classes('w-full h-40')
def add_trace():
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[random(), random(), random()]))
plot.update()
ui.button('Add trace', on_click=add_trace)
ui.run()
ui.run()

View File

@ -0,0 +1,42 @@
import plotly.graph_objects as go
from nicegui import ui
fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
import plotly.express as px
import pandas
df = px.data.gapminder()
df1 = df.query("country == 'United States'")
print(df1.columns)
fig = px.line(df1,
x="year",
y="lifeExp",
# color="continent",
title="A Plotly Express Figure",
markers=True,
# symbol="continent",
line_shape="linear"
)
# ['linear', 'hv', 'vh', 'hvh', 'vhv']
df2 = df.query("continent == 'Oceania'")
fig = px.bar(df2,
x="year",
y="pop",
color="country",
barmode="group"
)
ui.plotly(fig)
# ui.run()
import plotly.graph_objects as go
from nicegui import ui
fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
plot = ui.plotly(fig).classes('w-full h-40')
plot.on('plotly_click', ui.notify)
ui.run()

View File

@ -0,0 +1,5 @@
from nicegui import ui
ui.input('演示',value='默认值').props("outlined")
ui.run()

View File

@ -0,0 +1,14 @@
from nicegui import ui
from ex4nicegui.reactive import rxui
from ex4nicegui import to_ref,ref_computed,effect
content1 = to_ref('')
content2 = to_ref('')
result = ref_computed(lambda: content1.value+content2.value)
input1 = rxui.input("aaaaaaaa",value=content1)
input2 = ui.input("bbbbbbbbbb",value=content1)
label = rxui.label(result)
ui.run()

View File

@ -0,0 +1,4 @@
import plotly.express as px
import pandas
df = px.data.gapminder()
df.to_csv("gapminder.csv")

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
from nicegui import ui
import pandas as pd
from ex4nicegui import bi
from pyecharts.charts import Bar
df = pd.read_csv("gapminder.csv")
print(df.columns)
# ['Unnamed: 0', 'country', 'continent', 'year', 'lifeExp', 'pop',
# 'gdpPercap', 'iso_alpha', 'iso_num']
ds = bi.data_source(df)
# select_year = df.ui_select("year")
select_continent =ds.ui_select("continent")
ds.ui_select("country")
@df.ui_echarts
def bar(data: pd.DataFrame):
data = data.groupby(["year"])["gdpPercap"].sum().reset_index()
return Bar().add_xaxis(data["year"].tolist()).add_yaxis("gdpPercap",data["gdpPercap"].tolist())
ui.run()

View File

@ -0,0 +1,12 @@
from nicegui import ui
from ex4nicegui import ref_computed, effect, to_ref
from ex4nicegui.reactive import rxui
# 定义响应式数据
r_input = to_ref("")
# 按照 nicegui 使用方式传入响应式数据即可
rxui.input(value=r_input)
rxui.label(r_input)
ui.run()

View File

@ -0,0 +1,116 @@
from nicegui import ui
import pandas as pd
import numpy as np
from ex4nicegui import bi
from ex4nicegui.reactive import rxui
from ex4nicegui import effect, effect_refreshable
from pyecharts.charts import Bar
# data ready
def gen_data():
np.random.seed(265)
field1 = ["a1", "a2", "a3", "a4"]
field2 = [f"name{i}" for i in range(1, 11)]
df = (
pd.MultiIndex.from_product([field1, field2], names=["cat", "name"])
.to_frame()
.reset_index(drop=True)
)
df[["idc1", "idc2"]] = np.random.randint(50, 1000, size=(len(df), 2))
return df
df = gen_data()
# 创建数据源
ds = bi.data_source(df)
# ui
ui.query(".nicegui-content").classes("items-stretch no-wrap")
with ui.row().classes("justify-evenly"):
# 基于数据源 `ds` 创建界面组件
ds.ui_select("cat").classes("min-w-[10rem]")
ds.ui_select("name").classes("min-w-[10rem]")
with ui.grid(columns=2):
# 使用字典配置图表
@ds.ui_echarts
def bar1(data: pd.DataFrame):
data = data.groupby("name").agg({"idc1": "sum", "idc2": "sum"}).reset_index()
return {
"xAxis": {"type": "value"},
"yAxis": {
"type": "category",
"data": data["name"].tolist(),
"inverse": True,
},
"legend": {"textStyle": {"color": "gray"}},
"series": [
{"type": "bar", "name": "idc1", "data": data["idc1"].tolist()},
{"type": "bar", "name": "idc2", "data": data["idc2"].tolist()},
],
}
bar1.classes("h-[20rem]")
# 使用pyecharts配置图表
@ds.ui_echarts
def bar2(data: pd.DataFrame):
data = data.groupby("name").agg({"idc1": "sum", "idc2": "sum"}).reset_index()
return (
Bar()
.add_xaxis(data["name"].tolist())
.add_yaxis("idc1", data["idc1"].tolist())
.add_yaxis("idc2", data["idc2"].tolist())
)
bar2.classes("h-[20rem]")
# 绑定点击事件,即可实现跳转
@bar2.on_chart_click
def _(e: rxui.echarts.EChartsMouseEventArguments):
ui.open(f"/details/{e.name}", new_tab=True)
# 利用响应式机制,你可以随意组合原生 nicegui 组件
label_a1_total = ui.label("")
# 当 ds 有变化,都会触发此函数
@effect
def _():
# filtered_data 为过滤后的 DataFrame
df = ds.filtered_data
total = df[df["cat"] == "a1"]["idc1"].sum()
label_a1_total.text = f"idc1 total(cat==a1):{total}"
# 你也可以使用 `effect_refreshable`,但需要注意函数中的组件每次都被重建
@effect_refreshable
def _():
df = ds.filtered_data
total = df[df["cat"] == "a2"]["idc1"].sum()
ui.label(f"idc1 total(cat==a2):{total}")
# 当点击图表系列时,跳转的页面
@ui.page("/details/{name}")
def details_page(name: str):
ui.label("This table data will not change")
ui.aggrid.from_pandas(ds.data.query(f'name=="{name}"'))
ui.label("This table will change when the homepage data changes. ")
@bi.data_source
def new_ds():
return ds.filtered_data[["name", "idc1", "idc2"]]
new_ds.ui_aggrid()
ui.run()

View File

@ -0,0 +1,32 @@
from nicegui import ui
from ex4nicegui.reactive import rxui
opts = {
"xAxis": {"type": "value", "boundaryGap": [0, 0.01]},
"yAxis": {
"type": "category",
"data": ["Brazil", "Indonesia", "USA", "India", "China", "World"],
},
"series": [
{
"name": "first",
"type": "bar",
"data": [18203, 23489, 29034, 104970, 131744, 630230],
},
{
"name": "second",
"type": "bar",
"data": [19325, 23438, 31000, 121594, 134141, 681807],
},
],
}
bar = rxui.echarts(opts)
def on_first_series_mouseover(e: rxui.echarts.EChartsMouseEventArguments):
ui.notify(f"on_first_series_mouseover:{e.seriesName}:{e.name}:{e.value}")
bar.on("mouseover", on_first_series_mouseover, query={"seriesName": "first"})
ui.run()

View File

@ -0,0 +1,34 @@
from nicegui import ui
from ex4nicegui import ref_computed, effect, to_ref
from ex4nicegui.reactive import rxui
r_input = to_ref("")
# ref_computed 创建只读响应式变量
# 函数中使用任意其他响应式变量,会自动关联
@ref_computed
def cp_echarts_opts():
return {
"title": {"text": r_input.value}, #字典中使用任意响应式变量,通过 .value 获取值
"xAxis": {
"type": "category",
"data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
"yAxis": {"type": "value"},
"series": [
{
"data": [120, 200, 150, 80, 70, 110, 130],
"type": "bar",
"showBackground": True,
"backgroundStyle": {"color": "rgba(180, 180, 180, 0.2)"},
}
],
}
input = rxui.input("输入内容,图表标题会同步", value=r_input)
# 通过响应式组件对象的 element 属性,获取原生 nicegui 组件对象
input.element.classes("w-full")
rxui.echarts(cp_echarts_opts)
ui.run()

View File

@ -0,0 +1,29 @@
from fastapi import FastAPI
import uvicorn
from nicegui import ui
app = FastAPI()
def fastapi(app:FastAPI):
@app.get('/')
def read_root():
return {'Hello': 'World'}
fastapi(app)
def nicegui(app: FastAPI) -> None:
@ui.page('/a')
def a():
ui.label("this is aaaaaaaaaaaaaaa")
@ui.page('/b')
def b():
ui.label("this is bbbbbbbbbbbbbbbbbbb")
ui.run_with(app)
nicegui(app)
def main():
# 使用uvicorn运行FastAPI应用指定主机地址和端口
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,41 @@
from fastapi import FastAPI
import uvicorn
from nicegui import ui
app = FastAPI()
def fastapi(app:FastAPI):
@app.get('/')
def read_root():
return {'Hello': 'World'}
fastapi(app)
def nicegui(app: FastAPI) -> None:
@ui.page('/a')
def a():
ui.label("this is aaaaaaaaaaaaaaa")
@ui.page('/b')
def b():
import plotly.express as px
df = px.data.gapminder()
df2007 = df.query("year == 2007")
print(df2007.head())
fig = px.scatter(df2007,
x="gdpPercap",
y="lifeExp",
color="continent",
title="A Plotly Express Figure",
size='pop',
size_max=60
)
ui.plotly(fig)
ui.run_with(app)
nicegui(app)
def main():
# 使用uvicorn运行FastAPI应用指定主机地址和端口
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,23 @@
from fastapi import FastAPI
import uvicorn
from fastapi.responses import HTMLResponse
from pathlib import Path
app = FastAPI()
def run_with(app:FastAPI):
@app.get('/a')
def a():
return {'Hello': 'World'}
@app.get('/b')
def b():
return HTMLResponse(Path('static/b.html').read_bytes())
def main():
# 使用uvicorn运行FastAPI应用指定主机地址和端口
run_with(app)
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</body>
</html>

View File

@ -1,19 +0,0 @@
from fastapi import FastAPI
from nicegui import app, ui
def init(fastapi_app: FastAPI) -> None:
@ui.page('/')
def show():
ui.label('Hello, FastAPI!')
# NOTE dark mode will be persistent for each user across tabs and server restarts
ui.dark_mode().bind_value(app.storage.user, 'dark_mode')
ui.checkbox('dark mode').bind_value(app.storage.user, 'dark_mode')
ui.run_with(
fastapi_app,
mount_path='/gui', # NOTE this can be omitted if you want the paths passed to @ui.page to be at the root
storage_secret='pick your private secret here', # NOTE setting a secret is optional but allows for persistent storage per user
)

View File

@ -1,21 +0,0 @@
#!/usr/bin/env python3
import frontend
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get('/')
def read_root():
return {'Hello': 'World'}
frontend.init(app)
def main():
# 使用uvicorn运行FastAPI应用指定主机地址和端口
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
if __name__ == "__main__":
main()

View File

@ -2,4 +2,8 @@
https://nicegui.io/documentation
http://www.quasarchs.com/
1 视频教程
https://www.bilibili.com/video/BV1EM4y1x7CM/?spm_id_from=333.337.search-card.all.click&vd_source=311a862c74a77082f872d2e1ab5d1523
https://www.bilibili.com/video/BV1EM4y1x7CM/?spm_id_from=333.337.search-card.all.click&vd_source=311a862c74a77082f872d2e1ab5d1523
2 ex4nicegui变种
https://github.com/CrystalWindSnake/ex4nicegui#%E6%95%99%E7%A8%8B
https://gitee.com/carson_add/ex4nicegui?_from=gitee_search

View File

@ -0,0 +1,2 @@
1 视频教程
https://www.bilibili.com/video/BV1UJ411A7Fs?p=4&vd_source=311a862c74a77082f872d2e1ab5d1523