Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the simply-static domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/html/wp-includes/functions.php on line 6121
2023 年 8 月 – 第 2 页

用streamlit创建实时看板

如何使用 Streamlit 构建实时仪表板

import time  # to simulate a real time data, time loop

import numpy as np  # np mean, np random
import pandas as pd  # read csv, df manipulation
import plotly.express as px  # interactive charts
import streamlit as st  # 🎈 data web app development

st.set_page_config(
    page_title="Real-Time Data Science Dashboard",
    page_icon="✅",
    layout="wide",
)

# read csv from a github repo
dataset_url = "https://raw.githubusercontent.com/Lexie88rus/bank-marketing-analysis/master/bank.csv"

# read csv from a URL
@st.experimental_memo
def get_data() -> pd.DataFrame:
    return pd.read_csv(dataset_url)

df = get_data()

# dashboard title
st.title("Real-Time / Live Data Science Dashboard")

# top-level filters
job_filter = st.selectbox("Select the Job", pd.unique(df["job"]))

# creating a single-element container
placeholder = st.empty()

# dataframe filter
df = df[df["job"] == job_filter]

# near real-time / live feed simulation
for seconds in range(200):

    df["age_new"] = df["age"] * np.random.choice(range(1, 5))
    df["balance_new"] = df["balance"] * np.random.choice(range(1, 5))

    # creating KPIs
    avg_age = np.mean(df["age_new"])

    count_married = int(
        df[(df["marital"] == "married")]["marital"].count()
        + np.random.choice(range(1, 30))
    )

    balance = np.mean(df["balance_new"])

    with placeholder.container():

        # create three columns
        kpi1, kpi2, kpi3 = st.columns(3)

        # fill in those three columns with respective metrics or KPIs
        kpi1.metric(
            label="Age ⏳",
            value=round(avg_age),
            delta=round(avg_age) - 10,
        )
        
        kpi2.metric(
            label="Married Count 💍",
            value=int(count_married),
            delta=-10 + count_married,
        )
        
        kpi3.metric(
            label="A/C Balance $",
            value=f"$ {round(balance,2)} ",
            delta=-round(balance / count_married) * 100,
        )

        # create two columns for charts
        fig_col1, fig_col2 = st.columns(2)
        with fig_col1:
            st.markdown("### First Chart")
            fig = px.density_heatmap(
                data_frame=df, y="age_new", x="marital"
            )
            st.write(fig)
            
        with fig_col2:
            st.markdown("### Second Chart")
            fig2 = px.histogram(data_frame=df, x="age_new")
            st.write(fig2)

        st.markdown("### Detailed Data View")
        st.dataframe(df)
        time.sleep(1)

MagicMirror²魔镜安装

魔镜可以手动安装,也可以使用自动安装程序安装。2020 年初,决定从 MagicMirror² 核心存储库中删除自动安装程序,并将其移动到社区维护的单独存储库。有关此决定的更多信息,请查看问题#1860在 GitHub 上。

因此,唯一官方支持的安装方式是使用手动安装。使用外部安装脚本的风险由您自行承担,但可以使该过程变得容易得多。可用的自动安装程序可以在以下位置找到:替代安装方法。

手动安装
下载并安装最新的 Node.js 版本:
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
克隆存储库并签出主分支:git clone https://github.com/MichMich/MagicMirror
输入存储库:cd MagicMirror/
安装应用程序:npm run install-mm
复制配置示例文件:cp config/config.js.sample config/config.js
启动应用程序:仅供服务器使用:
。npm run start
npm run server
注意

安装步骤将花费很长时间,通常很少或没有终端响应!对于RPi3,这是~10分钟,对于Rpi2~25分钟。不要打断,否则您可能会被覆盆子果酱弄到。 💔npm run install-mm

替代安装方法
以下安装方法不由 MagicMirror² 核心团队维护。使用这些脚本和方法的风险由您自行承担。

自动安装脚本
Sam(@sdetweil,MagicMirror² 框架的长期贡献者)维护了一个易于使用的安装和更新脚本:https://github.com/sdetweil/MagicMirror_scripts
魔镜包管理器是一个命令行界面,旨在简化 MagicMirror 模块的安装、拆卸和维护。
码头工人镜像
MagicMirror² 可以使用码头工人.前往此存储库了解更多信息。
Kubernetes Helm Chart
如果你想在 kubernetes 集群中运行 MagicMirror²(在仅服务器模式下),那么看看这个魔镜掌舵图.
MagicMirrorOS
这是一个基于Raspberry Pi OS的完整操作系统。因此,您无需下载Raspberry Pi OS并将其放在SD卡上,而是可以使用MagicMirrorOS相反。它开箱即用,默认设置为MagicMirror,在引擎盖下它使用码头工人设置.
其他操作系统
窗户:
要让MagicMirror软件在Windows上运行,除了上述步骤外,您还必须做两件事:

4一.在供应商和字体目录中安装依赖项:

Powershell:

cd fonts; npm install; cd ..
cd vendor; npm install; cd ..
命令提示符:

cd fonts && npm install && cd ..
cd vendor && npm install && cd ..
否则,启动魔镜时屏幕将保持黑色。

5一.修复文件中的启动脚本:package.json

导航到该文件package.json
找到它说的地方
"start": "DISPLAY=\"${DISPLAY:=:0}\" ./node_modules/.bin/electron js/electron.js",
"start:dev": "DISPLAY=\"${DISPLAY:=:0}\" ./node_modules/.bin/electron js/electron.js dev",
并将其替换为
"start": ".\\node_modules\\.bin\\electron js\\electron.js",
"start:dev": ".\\node_modules\\.bin\\electron js\\electron.js dev",
否则,程序将无法启动,但将显示以下错误消息:"'DISPLAY' is not recognized as an internal or external command, operable program or batch file."

用法
请注意以下几点:

npm start无法通过 SSH 工作。但你可以改用。
这将启动远程显示器上的镜像。DISPLAY=:0 nohup npm start &
如果你想在你的树莓派上调试,你可以使用它将在启用开发工具的情况下启动MM。npm run start:dev
要在镜像模式下访问工具栏菜单,请按键。ALT
要从镜像模式切换 (Web),请使用 或 并选择 。Developer ToolsCTRL-SHIFT-IALTView
仅服务器
在某些情况下,您希望在没有实际应用程序窗口的情况下启动应用程序。在这种情况下,您可以通过手动运行 来在仅服务器模式下启动 MagicMirror² 。这将启动服务器,之后您可以在所选浏览器中打开应用程序。详细说明如下。npm run server

重要

确保在服务器配置中将接口/ip () 列入白名单,否则将不允许它连接到服务器。您还需要将本地主机字段设置为 ,以便 RPi 侦听所有接口,而不仅仅是(默认)。ipWhitelistaddress0.0.0.0localhost

let config = {
	address: "0.0.0.0",	// default is "localhost"
	port: 8080,		// default
	ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:172.17.0.1"], // default -- need to add your IP here
	...
};
仅限客户端
这是当您已经有一台服务器远程运行并希望您的 RPi 作为独立客户端连接到此实例时,以显示来自服务器的 MM。然后从您的 RPi 中,您可以使用以下命令运行它: .(指定服务器的 IP 地址和端口号)node clientonly --address 192.168.1.5 --port 8080
然后来到我们魔镜的config文件(路径:/home/pi/MagicMirror/config.js),然后用文本编辑器打开:
把原本language处的“en”改成“zh-cn”,区域设为 zh,就是中文啦

用树莓派打造一个超薄魔镜的简单教程 | OneV’s Den (onevcat.com)

第 12 章 – Magic mirror 初探 (vbird.tw)

pandas环比和同比分析

import pandas as pd
import random

date_M = list(pd.date_range('1/1/2019', periods=24, freq='M')) #生成日期
mony = [random.randint(18000,20000) for i in range(0,24)] #随机生成销售额
data = pd.DataFrame({'date_M':date_M,'mony':mony}) #构建一个dataframe
data['huanbi_03'] = data.mony.pct_change()
data.fillna(0,inplace=True) #Null值填充
print(data)
第一步:生成测试数据

#生成测试数据
import pandas as pd
import random

date_M = list(pd.date_range('1/1/2019', periods=24, freq='M')) #生成日期
mony = [random.randint(18000,20000) for i in range(0,24)] #随机生成销售额
data = pd.DataFrame({'date_M':date_M,'mony':mony}) #构建一个dataframe
第二步:计算环比增长

这里有三个方法,我们逐一介绍。

----------------------------------------------------------
#方法1
----------------------------------------------------------
'''
 #升序排列-按照日期
data.sort_values(by=['date_M'],inplace=True)

 #新增列 -'huanbi' 环比的意思
data['huanbi_01']=0

#计算环比列数值
for i in range(0,len(data)):
    if i == 0:
        data['huanbi_01'][i] = 'null'
    else:
        data['huanbi_01'][i] = format((data['mony'][i] - data['mony'][i-1])/data['mony'][i-1],'.2%')
        #format(res,'.2%') 小数格式化为百分数
'''
----------------------------------------------------------
#方法2:
使用diff(periods=1, axis=0)) 一阶差分函数
periods:移动的幅度 默认值为1
axis:移动的方向,{0 or ‘index’, 1 or ‘columns’},如果为0或者’index’,则上下移动,如果为1或者’columns’,则左右移动。默认列向移动
----------------------------------------------------------
'''
data['huanbi_02'] = data['mony']/(data['mony']-data['mony'].diff())-1

data.fillna(0,inplace=True) #Null值填充

'''
----------------------------------------------------------
#方法3:
使用pct_change()
----------------------------------------------------------
'''
data['huanbi_03'] = data.mony.pct_change()

data.fillna(0,inplace=True) #Null值填充