아래는 라이브 인구 데이터를 검색하는 간단한 스크립트입니다. 주기적으로 업데이트하고 플롯 그림을 업데이트합니다.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
# Retrieve data
link = requests.get("https://countrymeters.info/en/World").text
table = pd.read_html(link)[0]
table = table
figure = table.iplot(asFigure=True, kind='bar',xTitle='Source: World',yTitle='Live Pop',title='Population')
# Dash app
app = dash.Dash(external_stylesheets=[dbc.themes.LUX])
# Bootstrap CSS
app.css.append_css({"external_url": "https://codepen.io/amyoshino/pen/jzXypZ.css"})
link = session.get("https://countrymeters.info/en/World").text
app.layout = html.Div(children=[
html.H1("Population Data Scrape"),
html.Div(children=
'''
A summary of the latest population data across the globe.
''' ),
# Graph 1
html.Div([
dcc.Tabs([ #Tab 1
dcc.Tab(label="Population Data", children=[
html.Div([
dcc.Graph(
id = "Data",
figure = table.iplot(asFigure=True, kind='bar',xTitle='Source: World',yTitle='Live Pop',title='Population')
),
dcc.Interval(
id="4secinterval",
interval="4000",
n_intervals=0
)], className = "six columns"),
]),
])
])
])
# Update graph
@app.callback(Output("Data", "figure"),
[Input("4secinterval", "n_intervals")])
def draw_figure(n):
test = session.get("https://countrymeters.info/en/World").text
table = pd.read_html(test)[0]
table = table
figure = table.iplot(asFigure=True, kind='bar',xTitle='Source: World',yTitle='Live Pop',title='Population')
return figure
if __name__ == "__main__":
app.run_server(debug=False)
내 코드의 "그래프 업데이트"섹션에서 그래프를 업데이트하려면 웹 스크랩을 다시 호출하여 최신 데이터를 검색하고 전체 함수에서 정의해야합니다. 이전에 함수를 정의하고 사용하려고 시도했습니다.
@app.callback(Output("Data", "figure"),
[Input("4secinterval", "n_intervals")])
draw_figure(n)
나는 단지 그림을 반환하기를 바랐지만 이것은 작동하지 않습니다. 플롯 / 대시에서 더 짧은 방식으로 그림을 업데이트 할 수있는 방법이 있습니까 (즉, 데이터를 다시 긁어 내고 형식을 지정할 필요없이)?
여기서 캐치는 dcc.Graph
섹션에 있습니다. table.iplot()
검색 섹션에서 테이블이 전역 변수 로 정의 된 전역 변수를 호출합니다 .
모든 함수를 별도의 파일에`useful_functions.py '라고 입력하십시오.
def draw_graph():
link = requests.get("https://countrymeters.info/en/World").text
table = pd.read_html(link)[0]
table = table
figure = table.iplot(asFigure=True, kind='bar',xTitle='Source: World',yTitle='Live Pop',title='Population')
return figure
the_graph = draw_graph()
이제 위와 같이 주 파일에서 table과 figure의 전역 선언을 제거하십시오. 그래프를 표시하려면 그래프 섹션에서 draw_graph()
함수를 다음과 같이 호출하십시오 .
import useful_functions as uf
<rest of the html app code>
dcc.Graph(
id = "graph_id",
figure = uf.the_graph
),
로드시 처음으로 그래프를 호출합니다. 이제 새로 고침 비트의 경우 callback
다음과 같습니다.
@app.callback(Output("Data", "figure"),
[Input("4secinterval", "n_intervals")])
def draw_figure(n):
fig = uf.draw_graph()
return fig
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다