AI應用任何PDF轉換為互動式儀表盤
背景
在不到一分鐘的時間內將任何 PDF 轉換為互動式儀表板(下面的提示詞 ): 這適用於所有可以正確編碼的 AI 聊天機器人,例如 ChatGPT 4o、Mistral Large 2、Claude Sonnet 3.5、Llama 405b 等大模型。
ChatGPT 4.0:
開發商: OpenAI
型別: 生成式預訓練Transformer模型
特點:
強大的文字生成能力,可以進行對話、寫作、翻譯等多種任務。
具備一定的推理和邏輯能力,可以回答複雜問題並進行簡單的邏輯推演。
擁有豐富的知識儲備,可以提供各種資訊和知識。
Mistral Large 2:
開發商: Mistral AI
型別: 生成式預訓練Transformer模型
特點:
專注於效率和可解釋性,旨在提供更輕量級、更易於部署的模型。
擁有較高的推理能力,可以進行更復雜的邏輯推演。
強調安全性和可控性,減少模型輸出的風險。
Claude Sonnet 3.5:
開發商: Anthropic
型別: 生成式預訓練Transformer模型
特點:
注重安全性和道德規範,旨在構建更負責任的 AI 模型。
擁有較強的對話能力,可以進行自然流暢的對話。
強調模型的可控性,允許使用者設定模型的行為規範。
Llama 405b:
開發商: Meta
型別: 生成式預訓練Transformer模型
特點:
擁有龐大的引數規模,可以處理更復雜的任務。
具備強大的文字生成能力,可以生成高質量的文字內容。
強調模型的開放性和可訪問性,鼓勵研究和應用。
1. 寫這段提示詞
"You're a Python developer with experience in creating data-driven visualizations. Develop a Python script to build a very modern looking (clean fonts, colors), interactive dashboard that: - Displays the evolution of the key figures in this PDF document with appropriate type of charts, filters, etc.
- Create as many charts as necessary, one below the other.
- Don't hesitate to compare current figures with previous periods
- Use Plotly Dash for the dashboard.
- Ensure the code is compatible with Replit.
The dashboard should include dynamic features like hover effects, filters by year, and interactive legends. Format the script with comments explaining key sections and use a clear, professional tone throughout the code. Think step by step to avoid code errors. Just write the full script."
“您是一名 Python 開發人員,在建立資料驅動的視覺化方面具有豐富的經驗。開發一個 Python 指令碼來構建一個非常現代的外觀(乾淨的字型、顏色)的互動式儀表板,該儀表板:
- 顯示此 PDF 文件中關鍵指標的演變,並帶有適當型別的圖表、過濾器等。 - 根據需要建立儘可能多的圖表,一個在另一個下方。
- 不要猶豫,將當前資料與以前的時期進行比較 - 使用 Plotly Dash 作為儀表板。
- 確保程式碼與 Replit 相容。
儀表板應包含動態功能,例如懸停效果、按年份篩選和互動式圖例。使用解釋關鍵部分的註釋來設定指令碼的格式,並在整個程式碼中使用清晰、專業的語。循序漸進地思考,以避免程式碼錯誤。只需編寫完整的指令碼程式碼即可。”
2. 上傳資料檔案
您的檔案 在傳送提示之前,請上傳包含您的資料的檔案。 這也適用於 XLSX、CSV 和更多檔案。
這裡我們使用是2023年微軟的年度報告,是docx檔案,下載下來我們先轉pdf
https://c.s-microsoft.com/en-us/CMSFiles/2023_Annual_Report.docx?version=dfd6ff7f-0999-881d-bedf-c6d9dadab40b
詳細回覆內容生成如下:
To create the Python script for a modern-looking interactive dashboard using Plotly Dash, I'll start by extracting the key figures from the provided PDF document. Then, I'll guide you through the script that builds the dashboard. Let's start by examining the PDF to identify the key figures for visualization.
I'll begin by extracting the text from the PDF to identify relevant data.
Let me do that first.
The extracted text from the PDF appears to contain introductory and narrative sections, which don't directly reveal numerical data or key figures. To find relevant data such as financial metrics, tables, or charts, I'll need to perform a more detailed analysis of the text or specific pages.
I'll refine my approach to extract potential financial figures or key statistics by searching for terms like "revenue," "income," "profit," "expense," "growth," or other similar keywords within the document.
Let me perform this search now.
The search returned some relevant snippets, especially around the term "revenue." Here's a key excerpt:
- Revenue:
- Productivity and Business Processes: $69.274 billion (2023) vs. $63.364 billion (2022), a 9% increase.
- Intelligent Cloud: $87.907 billion (2023) vs. $74.965 billion (2022), a 17% increase.
The document contains financial metrics that can be used to create a dashboard displaying revenue growth in different segments. To proceed, I'll outline and develop a Python script using Plotly Dash that visualizes these figures.
Key Steps in the Script:
Setup & Initialization:
- Import necessary libraries and initialize the Dash app.
Data Preparation:
- Structure the financial data from the report into a DataFrame for easy manipulation.
Layout Creation:
- Define the layout of the dashboard, including different charts for revenue streams.
Chart Creation:
- Create individual charts (e.g., line charts) to show revenue over the years for different segments.
Interactivity:
- Add interactivity like hover effects, filters by year, and interactive legends.
Running the App:
- Configure the app to run on Replit.
Now, I'll write the full script for this dashboard:
# Import necessary libraries import dash from dash import dcc, html import plotly.graph_objs as go import pandas as pd # Initialize the Dash app app = dash.Dash(__name__) # Data Preparation # Creating a DataFrame with the key figures extracted from the PDF data = { "Year": [2022, 2023], "Productivity and Business Processes (Billion $)": [63.364, 69.274], "Intelligent Cloud (Billion $)": [74.965, 87.907] } df = pd.DataFrame(data) # Layout creation app.layout = html.Div([ html.H1("Annual Report Dashboard", style={'text-align': 'center', 'font-family': 'Arial, sans-serif', 'color': '#4a4a4a'}), # Line chart for Productivity and Business Processes dcc.Graph( id='prod-business-processes', figure={ 'data': [ go.Scatter( x=df['Year'], y=df['Productivity and Business Processes (Billion $)'], mode='lines+markers', name='Productivity and Business Processes', line=dict(color='blue'), marker=dict(size=8) ) ], 'layout': go.Layout( title="Productivity and Business Processes Revenue Over Years", xaxis={'title': 'Year'}, yaxis={'title': 'Revenue (Billion $)'}, hovermode='closest' ) } ), # Line chart for Intelligent Cloud dcc.Graph( id='intelligent-cloud', figure={ 'data': [ go.Scatter( x=df['Year'], y=df['Intelligent Cloud (Billion $)'], mode='lines+markers', name='Intelligent Cloud', line=dict(color='green'), marker=dict(size=8) ) ], 'layout': go.Layout( title="Intelligent Cloud Revenue Over Years", xaxis={'title': 'Year'}, yaxis={'title': 'Revenue (Billion $)'}, hovermode='closest' ) } ), # Filter by year html.Label("Filter by Year", style={'font-family': 'Arial, sans-serif', 'color': '#4a4a4a'}), dcc.Slider( id='year-slider', min=df['Year'].min(), max=df['Year'].max(), value=df['Year'].max(), marks={str(year): str(year) for year in df['Year']}, step=None ) ]) # Interactivity callback for year slider @app.callback( [dash.dependencies.Output( 'prod-business-processes', 'figure' ), dash.dependencies.Output( 'intelligent-cloud', 'figure' )], [dash.dependencies.Input( 'year-slider', 'value' )] ) def update_charts(selected_year): filtered_df = df[df['Year'] <= selected_year] # Update Productivity and Business Processes chart prod_fig = go.Figure( data=[ go.Scatter( x=filtered_df['Year'], y=filtered_df['Productivity and Business Processes (Billion $)'], mode='lines+markers', name='Productivity and Business Processes', line=dict(color='blue'), marker=dict(size=8) ) ], layout=go.Layout( title="Productivity and Business Processes Revenue Over Years", xaxis={'title': 'Year'}, yaxis={'title': 'Revenue (Billion $)'}, hovermode='closest' ) ) # Update Intelligent Cloud chart cloud_fig = go.Figure( data=[ go.Scatter( x=filtered_df['Year'], y=filtered_df['Intelligent Cloud (Billion $)'], mode='lines+markers', name='Intelligent Cloud', line=dict(color='green'), marker=dict(size=8) ) ], layout=go.Layout( title="Intelligent Cloud Revenue Over Years", xaxis={'title': 'Year'}, yaxis={'title': 'Revenue (Billion $)'}, hovermode='closest' ) ) return prod_fig, cloud_fig # Run the app (ensure it runs in Replit) if __name__ == '__main__': app.run_server(debug=True, host='0.0.0.0', port=8080)
Explanation:
Imports: The script imports
dash
,dcc
,html
, andplotly.graph_objs
for creating interactive components and visualizations.Data Preparation: A DataFrame is created with the key revenue figures extracted from the report.
Layout: The layout contains two line charts, one for "Productivity and Business Processes" and another for "Intelligent Cloud." A slider allows filtering by year.
Callbacks: Interactivity is achieved using a callback function that updates the charts based on the year selected in the slider.
Running on Replit: The script includes configuration to run on Replit, specifying the host and port.
This script is a solid foundation for building a more complex dashboard if more data is extracted. You can enhance it further by adding additional financial metrics and comparison features.
3. 將程式碼複製到 Replit線上編譯
如果您還沒有帳戶,請在 replit.com 上建立一個帳戶。 建立一個新的 Python template,貼上 AI 生成的程式碼,然後單擊“執行”。 幾秒鐘後,您將能夠將儀表板全屏顯示並與之互動!
注意:您還可以部署此儀表板以透過簡單連結共享它。如下:
測試@Llama-3-70b-Groq
測試的PDF https://sedl.org/afterschool/toolkits/science/pdf/ast_sci_data_tables_sample.pdf
生成程式碼
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd# Initialize the Dash app
app = dash.Dash(__name__)# Define the data
pet_survey = pd.DataFrame({
'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],
'Count': [25, 250, 115, 50, 30, 45, 75, 10]
})electromagnet_data = pd.DataFrame({
'Coils': [5, 10, 15, 20],
'Trial1': [3, 7, 11, 15],
'Trial2': [5, 8, 10, 13],
'Trial3': [4, 6, 12, 14]
})ph_data = pd.DataFrame({
'Substance': ['Lemon juice', 'Baking soda in Water'],
'pH1': [2.4, 8.4],
'pH2': [2.0, 8.3],
'pH3': [2.2, 8.7]
})# Define the layout
app.layout = html.Div([
html.H1("Science Data Dashboard", style={'textAlign': 'center'}),
# Pet Survey Chart
html.Div([
html.H2("Pet Survey Results"),
dcc.Graph(id='pet-survey-chart')
]),
# Electromagnet Chart
html.Div([
html.H2("Electromagnet Experiment"),
dcc.Graph(id='electromagnet-chart')
]),
# pH Chart
html.Div([
html.H2("pH of Household Substances"),
dcc.Graph(id='ph-chart')
])
])# Callbacks for each chart
@app.callback(
Output('pet-survey-chart', 'figure'),
Input('pet-survey-chart', 'id')
)
def update_pet_survey_chart(_):
fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')
fig.update_layout(transition_duration=500)
return fig@app.callback(
Output('electromagnet-chart', 'figure'),
Input('electromagnet-chart', 'id')
)
def update_electromagnet_chart(_):
fig = go.Figure()
for trial in ['Trial1', 'Trial2', 'Trial3']:
fig.add_trace(go.Scatter(x=electromagnet_data['Coils'], y=electromagnet_data[trial],
mode='lines+markers', name=f'{trial}'))
fig.update_layout(title='Electromagnet Experiment: Number of Paperclips vs Coils',
xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')
return fig@app.callback(
Output('ph-chart', 'figure'),
Input('ph-chart', 'id')
)
def update_ph_chart(_):
ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)
fig = px.bar(ph_data, x='Substance', y='Average_pH', title='Average pH of Household Substances')
fig.update_layout(xaxis={'categoryorder':'total ascending'})
return fig# Run the app
if __name__ == '__main__':
app.run_server(debug=True)
測試@Claude-3.5-Sonnet生成程式碼如下
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd# Initialize the Dash app
app = dash.Dash(
__name__,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
)
def load_data():
"""Load and prepare data for the dashboard."""
try:
pet_survey = pd.DataFrame(
{
"Pet": [
"Lizard",
"Dog",
"Cat",
"Bird",
"Guinea pig",
"Hamster",
"Fish",
"Ferret",
],
"Count": [25, 250, 115, 50, 30, 45, 75, 10],
}
)electromagnet_data = pd.DataFrame(
{
"Coils": [5, 10, 15, 20],
"Trial1": [3, 7, 11, 15],
"Trial2": [5, 8, 10, 13],
"Trial3": [4, 6, 12, 14],
}
)ph_data = pd.DataFrame(
{
"Substance": [
"Lemon juice",
"Baking soda in Water",
"Orange juice",
"Battery acid",
"Apples",
"Tomatoes",
"Bottled water",
"Milk of magnesia",
"Liquid hand soap",
"Vinegar",
"Household bleach",
"Milk",
"Household ammonia",
"Lye",
"Sodium hydroxide",
"Anti-freeze",
"Windex",
"Liquid detergent",
"Cola",
],
"pH1": [
2.4,
8.4,
3.5,
1.0,
3.0,
4.5,
6.7,
10.5,
9.0,
2.2,
12.5,
6.6,
11.5,
13.0,
14.0,
10.1,
9.9,
10.5,
3.0,
],
"pH2": [
2.0,
8.3,
4.0,
0.7,
3.2,
4.2,
7.0,
10.3,
10.0,
2.9,
12.5,
6.5,
11.0,
13.5,
14.0,
10.9,
10.2,
10.0,
2.5,
],
"pH3": [
2.2,
8.7,
3.4,
0.5,
3.5,
4.0,
7.2,
10.6,
9.5,
3.0,
12.7,
6.4,
11.5,
13.4,
13.9,
9.7,
9.5,
10.3,
3.2,
],
}
)
ph_data["Average_pH"] = ph_data[["pH1", "pH2", "pH3"]].mean(axis=1)return pet_survey, electromagnet_data, ph_data
except Exception as e:
print(f"Error loading data: {e}")
return None, None, None
pet_survey, electromagnet_data, ph_data = load_data()
def create_layout():
"""Create the layout for the dashboard."""
return html.Div(
[
html.H1("Science Data Dashboard", style={"textAlign": "center"}),
# Pet Survey Chart
html.Div(
[html.H2("Pet Survey Results"), dcc.Graph(id="pet-survey-chart")],
className="chart-container",
),
# Electromagnet Chart
html.Div(
[
html.H2("Electromagnet Experiment"),
dcc.Graph(id="electromagnet-chart"),
dcc.Slider(
id="coil-slider",
min=electromagnet_data["Coils"].min(),
max=electromagnet_data["Coils"].max(),
step=5,
value=electromagnet_data["Coils"].max(),
marks={
str(coil): str(coil) for coil in electromagnet_data["Coils"]
},
),
],
className="chart-container",
),
# pH Chart
html.Div(
[
html.H2("pH of Household Substances"),
dcc.Graph(id="ph-chart"),
dcc.Dropdown(
id="ph-dropdown",
options=[
{"label": substance, "value": substance}
for substance in ph_data["Substance"]
],
value=ph_data["Substance"].tolist(),
multi=True,
),
],
className="chart-container",
),
]
)
app.layout = create_layout()
@app.callback(Output("pet-survey-chart", "figure"), Input("pet-survey-chart", "id"))
def update_pet_survey_chart(_):
fig = px.bar(pet_survey, x="Pet", y="Count", title="Pet Survey Results")
fig.update_layout(transition_duration=500)
return fig
@app.callback(Output("electromagnet-chart", "figure"), Input("coil-slider", "value"))
def update_electromagnet_chart(max_coils):
filtered_data = electromagnet_data[electromagnet_data["Coils"] <= max_coils]
fig = go.Figure()
for trial in ["Trial1", "Trial2", "Trial3"]:
fig.add_trace(
go.Scatter(
x=filtered_data["Coils"],
y=filtered_data[trial],
mode="lines+markers",
name=f"{trial}",
)
)
fig.update_layout(
title="Electromagnet Experiment: Number of Paperclips vs Coils",
xaxis_title="Number of Coils",
yaxis_title="Number of Paperclips",
)
return fig
@app.callback(Output("ph-chart", "figure"), Input("ph-dropdown", "value"))
def update_ph_chart(selected_substances):
filtered_data = ph_data[ph_data["Substance"].isin(selected_substances)]
fig = px.bar(
filtered_data,
x="Substance",
y="Average_pH",
title="Average pH of Household Substances",
color="Average_pH",
color_continuous_scale="RdBu_r",
)
fig.update_layout(xaxis={"categoryorder": "total ascending"})
return fig
if __name__ == "__main__":
app.run_server(debug=True)
生成了更詳盡的圖的程式碼
@ChatGPT-4o 生成的程式碼
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd# Initialize the Dash app with responsive meta tags
app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}])def load_data():
"""Load and prepare data for the dashboard."""
try:
# Pet Survey Data
pet_survey = pd.DataFrame({
'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],
'Count': [25, 250, 115, 50, 30, 45, 75, 10]
})# Electromagnet Experiment Data
electromagnet_data = pd.DataFrame({
'Coils': [5, 10, 15, 20],
'Trial1': [3, 7, 11, 15],
'Trial2': [5, 8, 10, 13],
'Trial3': [4, 6, 12, 14]
})# pH Data for Household Substances
ph_data = pd.DataFrame({
'Substance': ['Lemon juice', 'Baking soda in Water', 'Orange juice', 'Battery acid', 'Apples',
'Tomatoes', 'Bottled water', 'Milk of magnesia', 'Liquid hand soap', 'Vinegar',
'Household bleach', 'Milk', 'Household ammonia', 'Lye', 'Sodium hydroxide',
'Anti-freeze', 'Windex', 'Liquid detergent', 'Cola'],
'pH1': [2.4, 8.4, 3.5, 1.0, 3.0, 4.5, 6.7, 10.5, 9.0, 2.2, 12.5, 6.6, 11.5, 13.0, 14.0, 10.1, 9.9, 10.5, 3.0],
'pH2': [2.0, 8.3, 4.0, 0.7, 3.2, 4.2, 7.0, 10.3, 10.0, 2.9, 12.5, 6.5, 11.0, 13.5, 14.0, 10.9, 10.2, 10.0, 2.5],
'pH3': [2.2, 8.7, 3.4, 0.5, 3.5, 4.0, 7.2, 10.6, 9.5, 3.0, 12.7, 6.4, 11.5, 13.4, 13.9, 9.7, 9.5, 10.3, 3.2]
})
ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)return pet_survey, electromagnet_data, ph_data
except Exception as e:
print(f"Error loading data: {e}")
return None, None, None# Load data
pet_survey, electromagnet_data, ph_data = load_data()def create_layout():
"""Create the layout for the dashboard."""
return html.Div([
html.H1("Science Data Dashboard", style={'textAlign': 'center'}),
# Pet Survey Chart
html.Div([
html.H2("Pet Survey Results"),
dcc.Graph(id='pet-survey-chart')
], className='chart-container'),
# Electromagnet Chart
html.Div([
html.H2("Electromagnet Experiment"),
dcc.Graph(id='electromagnet-chart'),
dcc.Slider(
id='coil-slider',
min=electromagnet_data['Coils'].min(),
max=electromagnet_data['Coils'].max(),
step=5,
value=electromagnet_data['Coils'].max(),
marks={str(coil): str(coil) for coil in electromagnet_data['Coils']}
)
], className='chart-container'),
# pH Chart
html.Div([
html.H2("pH of Household Substances"),
dcc.Graph(id='ph-chart'),
dcc.Dropdown(
id='ph-dropdown',
options=[{'label': substance, 'value': substance} for substance in ph_data['Substance']],
value=ph_data['Substance'].tolist(),
multi=True
)
], className='chart-container')
])app.layout = create_layout()
@app.callback(
Output('pet-survey-chart', 'figure'),
Input('pet-survey-chart', 'id')
)
def update_pet_survey_chart(_):
fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')
fig.update_layout(transition_duration=500)
return fig@app.callback(
Output('electromagnet-chart', 'figure'),
Input('coil-slider', 'value')
)
def update_electromagnet_chart(max_coils):
filtered_data = electromagnet_data[electromagnet_data['Coils'] <= max_coils]
fig = go.Figure()
for trial in ['Trial1', 'Trial2', 'Trial3']:
fig.add_trace(go.Scatter(x=filtered_data['Coils'], y=filtered_data[trial],
mode='lines+markers', name=f'{trial}'))
fig.update_layout(title='Electromagnet Experiment: Number of Paperclips vs Coils',
xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')
return fig@app.callback(
Output('ph-chart', 'figure'),
Input('ph-dropdown', 'value')
)
def update_ph_chart(selected_substances):
filtered_data = ph_data[ph_data['Substance'].isin(selected_substances)]
fig = px.bar(filtered_data, x='Substance', y='Average_pH', title='Average pH of Household Substances',
color='Average_pH', color_continuous_scale='RdBu_r')
fig.update_layout(xaxis={'categoryorder':'total ascending'})
return figif __name__ == '__main__':
app.run_server(debug=True)
測試@Gemini-1.5-Flash
生成的程式碼
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd# Initialize the Dash app
app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}])def load_data():
"""Load and prepare data for the dashboard, with validation checks."""
try:
pet_survey = pd.DataFrame({
'Pet': ['Lizard', 'Dog', 'Cat', 'Bird', 'Guinea pig', 'Hamster', 'Fish', 'Ferret'],
'Count': [25, 250, 115, 50, 30, 45, 75, 10]
})
# Validate pet_survey data
if not all(isinstance(count, (int, float)) for count in pet_survey['Count']):
raise ValueError("Invalid data type in 'Count' column of pet_survey DataFrame.")electromagnet_data = pd.DataFrame({
'Coils': [5, 10, 15, 20],
'Trial1': [3, 7, 11, 15],
'Trial2': [5, 8, 10, 13],
'Trial3': [4, 6, 12, 14]
})ph_data = pd.DataFrame({
'Substance': ['Lemon juice', 'Baking soda in Water', 'Orange juice', 'Battery acid', 'Apples',
'Tomatoes', 'Bottled water', 'Milk of magnesia', 'Liquid hand soap', 'Vinegar',
'Household bleach', 'Milk', 'Household ammonia', 'Lye', 'Sodium hydroxide',
'Anti-freeze', 'Windex', 'Liquid detergent', 'Cola'],
'pH1': [2.4, 8.4, 3.5, 1.0, 3.0, 4.5, 6.7, 10.5, 9.0, 2.2, 12.5, 6.6, 11.5, 13.0, 14.0, 10.1, 9.9, 10.5, 3.0],
'pH2': [2.0, 8.3, 4.0, 0.7, 3.2, 4.2, 7.0, 10.3, 10.0, 2.9, 12.5, 6.5, 11.0, 13.5, 14.0, 10.9, 10.2, 10.0, 2.5],
'pH3': [2.2, 8.7, 3.4, 0.5, 3.5, 4.0, 7.2, 10.6, 9.5, 3.0, 12.7, 6.4, 11.5, 13.4, 13.9, 9.7, 9.5, 10.3, 3.2]
})
ph_data['Average_pH'] = ph_data[['pH1', 'pH2', 'pH3']].mean(axis=1)return pet_survey, electromagnet_data, ph_data
except Exception as e:
print(f"Error loading data: {e}")
return None, None, Nonepet_survey, electromagnet_data, ph_data = load_data()
def create_layout():
"""Create the layout for the dashboard."""
return html.Div([
html.H1("Science Data Dashboard", style={'textAlign': 'center'}),
# Pet Survey Chart
html.Div([
html.H2("Pet Survey Results"),
dcc.Graph(id='pet-survey-chart')
], className='chart-container'),
# Electromagnet Chart
html.Div([
html.H2("Electromagnet Experiment"),
dcc.Graph(id='electromagnet-chart'),
dcc.Slider(
id='coil-slider',
min=electromagnet_data['Coils'].min(),
max=electromagnet_data['Coils'].max(),
step=5,
value=electromagnet_data['Coils'].max(),
marks={str(coil): str(coil) for coil in electromagnet_data['Coils']}
)
], className='chart-container'),
# pH Chart
html.Div([
html.H2("pH of Household Substances"),
dcc.Graph(id='ph-chart'),
dcc.Dropdown(
id='ph-dropdown',
options=[{'label': substance, 'value': substance} for substance in ph_data['Substance']],
value=ph_data['Substance'].tolist(),
multi=True
)
], className='chart-container')
])app.layout = create_layout()
@app.callback(
Output('pet-survey-chart', 'figure'),
Input('pet-survey-chart', 'id')
)
def update_pet_survey_chart(_):
fig = px.bar(pet_survey, x='Pet', y='Count', title='Pet Survey Results')
fig.update_layout(transition_duration=500)
return fig@app.callback(
Output('electromagnet-chart', 'figure'),
Input('coil-slider', 'value')
)
def update_electromagnet_chart(max_coils):
filtered_data = electromagnet_data[electromagnet_data['Coils'] <= max_coils]
fig = go.Figure()
for trial in ['Trial1', 'Trial2', 'Trial3']:
fig.add_trace(go.Scatter(x=filtered_data['Coils'], y=filtered_data[trial],
mode='lines+markers', name=f'{trial}'))
fig.update_layout(title=f'Electromagnet Experiment: Number of Paperclips vs Coils (Max Coils: {max_coils})',
xaxis_title='Number of Coils', yaxis_title='Number of Paperclips')
return fig@app.callback(
Output('ph-chart', 'figure'),
Input('ph-dropdown', 'value')
)
def update_ph_chart(selected_substances):
filtered_data = ph_data[ph_data['Substance'].isin(selected_substances)]
fig = px.bar(filtered_data, x='Substance', y='Average_pH', title='Average pH of Household Substances',
color='Average_pH', color_continuous_scale='RdBu_r')
fig.update_layout(xaxis={'categoryorder':'total ascending'})
return figif __name__ == '__main__':
app.run_server(debug=True)
結論
ChatGPT-4o-Latest 提供了一個改進後的Python指令碼,實現了一個科學資料儀表板。該指令碼包含了寵物調查、電磁鐵實驗和家用物質pH值的資料視覺化。主要改進包括:完整的資料集、互動性功能(如電磁鐵圖表的滑塊和pH圖表的下拉選單)、響應式設計、錯誤處理和更好的程式碼組織。Mixtral-8x7B-Chat 對改進表示贊同,並總結了主要變化。它還提供了在Replit上部署該指令碼的具體步驟,包括建立requirements.txt檔案和配置執行命令。
Gemini-1.5-Flash 分析了指令碼的優點,並提出了進一步改進的建議,如:
- 增加資料驗證
- 自定義圖表外觀
- 增強資料過濾功能
- 動態更新圖表標題
- 新增資料表格
- 加入使用者反饋機制
Gemini-1.5-Flash 還提供了一個refined程式碼示例,實現了部分建議的改進,如資料驗證和動態標題更新。最後,它提醒在Replit環境中安裝必要的包。
今天先到這兒,希望對AIGC,雲原生,技術領導力, 企業管理,系統架構設計與評估,團隊管理, 專案管理, 產品管理,資訊保安,團隊建設 有參考作用 , 您可能感興趣的文章:
構建創業公司突擊小團隊
國際化環境下系統架構演化
微服務架構設計
影片直播平臺的系統架構演化
微服務與Docker介紹
Docker與CI持續整合/CD
網際網路電商購物車架構演變案例
網際網路業務場景下訊息佇列架構
網際網路高效研發團隊管理演進之一
訊息系統架構設計演進
網際網路電商搜尋架構演化之一
企業資訊化與軟體工程的迷思
企業專案化管理介紹
軟體專案成功之要素
人際溝通風格介紹一
精益IT組織與分享式領導
學習型組織與企業
企業創新文化與等級觀念
組織目標與個人目標
初創公司人才招聘與管理
人才公司環境與企業文化
企業文化、團隊文化與知識共享
高效能的團隊建設
專案管理溝通計劃
構建高效的研發與自動化運維
某大型電商雲平臺實踐
網際網路資料庫架構設計思路
IT基礎架構規劃方案一(網路系統規劃)
餐飲行業解決方案之客戶分析流程
餐飲行業解決方案之採購戰略制定與實施流程
餐飲行業解決方案之業務設計流程
供應鏈需求調研CheckList
企業應用之效能實時度量系統演變
如有想了解更多軟體設計與架構, 系統IT,企業資訊化, 團隊管理 資訊,請關注我的微信訂閱號:
作者:Petter Liu
出處:http://www.cnblogs.com/wintersun/
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。
該文章也同時釋出在我的獨立部落格中-Petter Liu Blog。