PDF zu interaktivem Dashboard Prompt
Von Wikiprompt, der freien Prompt-Enzyklopädie
PDF zu interaktivem Dashboard Prompt Ein Prompt zur Erstellung eines Python-Skripts mit Plotly Dash für ein interaktives Dashboard aus einer PDF- oder Datendatei, mit Diagrammen, Filtern und dynamischen Funktionen.
Prompt-InhaltSpeichern
🌐
import dash
from dash import dcc, html, Input, Output, callback
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np
from datetime import datetime
# ==============================================================================
# DATA PREPARATION
# ==============================================================================
# Simulated data representing key figures from a typical financial/operational PDF
# In production, replace this with actual data extraction from your PDF
np.random.seed(42)
years = list(range(2019, 2025))
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
# Generate revenue data with growth trend
revenue_base = 1000000
revenue_growth = 0.15
revenue_data = []
for year in years:
for quarter in quarters:
seasonal_factor = {'Q1': 0.9, 'Q2': 1.1, 'Q3': 1.2, 'Q4': 1.0}[quarter]
base = revenue_base * (1 + revenue_growth) ** (year - 2019)
revenue_data.append({
'Year': year,
'Quarter': quarter,
'Period': f'{year}-{quarter}',
'Revenue': base * seasonal_factor * (1 + np.random.uniform(-0.05, 0.05)),
'Expenses': base * 0.7 * seasonal_factor * (1 + np.random.uniform(-0.05, 0.05)),
'Profit': base * 0.3 * seasonal_factor * (1 + np.random.uniform(-0.08, 0.08)),
'Customers': int(5000 * (1 + 0.2) ** (year - 2019) * (1 + np.random.uniform(-0.1, 0.1))),
'MarketShare': 15 + (year - 2019) * 2 + np.random.uniform(-1, 1)
})
df = pd.DataFrame(revenue_data)
# Calculate year-over-year metrics
df['YoY_Growth'] = df.groupby('Quarter')['Revenue'].pct_change() * 100
# Create summary DataFrame for annual comparisons
annual_df = df.groupby('Year').agg({
'Revenue': 'sum',
'Expenses': 'sum',
'Profit': 'sum',
'Customers': 'mean',
'MarketShare': 'mean'
}).reset_index()
annual_df['Profit_Margin'] = (annual_df['Profit'] / annual_df['Revenue']) * 100
annual_df['YoY_Revenue_Growth'] = annual_df['Revenue'].pct_change() * 100
# ==============================================================================
# DASHBOARD INITIALIZATION
# ==============================================================================
app = dash.Dash(__name__)
server = app.server # For Replit compatibility
# Modern color palette
colors = {
'background': '#F8F9FA',
'text': '#2C3E50',
'primary': '#3498DB',
'secondary': '#2ECC71',
'accent': '#E74C3C',
'grid': '#E5E8E8'
}
# ==============================================================================
# LAYOUT
# ==============================================================================
app.layout = html.Div(
style={
'backgroundColor': colors['background'],
'fontFamily': 'Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif',
'padding': '20px',
'maxWidth': '1400px',
'margin': '0 auto'
},
children=[
# Header
html.Div([
html.H1('Company Performance Dashboard',
style={'color': colors['text'], 'marginBottom': '5px'}),
html.P('Interactive analysis of key business metrics (2019-2024)',
style={'color': '#7F8C8D', 'marginTop': '0'})
], style={'textAlign': 'center', 'marginBottom': '30px'}),
# Filters
html.Div([
html.Label('Select Year:', style={'fontWeight': 'bold', 'color': colors['text']}),
dcc.Dropdown(
id='year-filter',
options=[{'label': str(year), 'value': year} for year in years],
value=years[-1],
multi=False,
clearable=False,
style={'width': '200px', 'marginLeft': '10px'}
),
html.Label('Select Metric:', style={'fontWeight': 'bold', 'color': colors['text'], 'marginLeft': '30px'}),
dcc.Dropdown(
id='metric-filter',
options=[
{'label': 'Revenue', 'value': 'Revenue'},
{'label': 'Expenses', 'value': 'Expenses'},
{'label': 'Profit', 'value': 'Profit'},
{'label': 'Customers', 'value': 'Customers'},
{'label': 'Market Share', 'value': 'MarketShare'}
],
value='Revenue',
multi=False,
clearable=False,
style={'width': '200px', 'marginLeft': '10px'}
)
], style={'display': 'flex', 'alignItems': 'center', 'marginBottom': '30px', 'flexWrap': 'wrap'}),
# Chart 1: Quarterly Trend with Year-over-Year Comparison
html.Div([
html.H3('Quarterly Performance Trend',
style={'color': colors['text'], 'marginBottom': '15px'}),
dcc.Graph(id='quarterly-trend-chart')
], style={'marginBottom': '40px'}),
# Chart 2: Annual Revenue vs Expenses (Bar Chart)
html.Div([
html.H3('Annual Revenue vs Expenses',
style={'color': colors['text'], 'marginBottom': '15px'}),
dcc.Graph(id='annual-bar-chart')
], style={'marginBottom': '40px'}),
# Chart 3: Profit Margin Evolution (Line Chart)
html.Div([
html.H3('Profit Margin Evolution',
style={'color': colors['text'], 'marginBottom': '15px'}),
dcc.Graph(id='profit-margin-chart')
], style={'marginBottom': '40px'}),
# Chart 4: Customer Growth (Area Chart)
html.Div([
html.H3('Customer Base Growth',
style={'color': colors['text'], 'marginBottom': '15px'}),
dcc.Graph(id='customer-growth-chart')
], style={'marginBottom': '40px'}),
# Chart 5: Market Share Comparison (Pie Chart)
html.Div([
html.H3('Market Share Distribution',
style={'color': colors['text'], 'marginBottom': '15px'}),
dcc.Graph(id='market-share-chart')
], style={'marginBottom': '40px'}),
# Footer
html.Footer(
'Data source: Company financial reports | Dashboard created with Plotly Dash',
style={'textAlign': 'center', 'color': '#7F8C8D', 'marginTop': '30px'}
)
]
)
# ==============================================================================
# CALLBACKS
# ==============================================================================
@callback(
Output('quarterly-trend-chart', 'figure'),
[Input('year-filter', 'value'),
Input('metric-filter', 'value')]
)
def update_quarterly_trend(selected_year, selected_metric):
"""Update quarterly trend chart based on selected year and metric"""
# Filter data for selected year and previous year for comparison
current_year_data = df[df['Year'] == selected_year]
previous_year_data = df[df['Year'] == selected_year - 1] if selected_year > years[0] else pd.DataFrame()
fig = go.Figure()
# Current year data
fig.add_trace(go.Scatter(
x=current_year_data['Quarter'],
y=current_year_data[selected_metric],
mode='lines+markers',
name=f'{selected_year}',
line=dict(color=colors['primary'], width=3),
marker=dict(size=10, color=colors['primary']),
hovertemplate=f'{selected_metric}: %{{y:,.0f}}<br>Quarter: %{{x}}<extra></extra>'
))
# Previous year data for comparison
if not previous_year_data.empty:
fig.add_trace(go.Scatter(
x=previous_year_data['Quarter'],
y=previous_year_data[selected_metric],
mode='lines+markers',
name=f'{selected_year - 1}',
line=dict(color=colors['secondary'], width=2, dash='dash'),
marker=dict(size=8, color=colors['secondary']),
hovertemplate=f'{selected_metric}: %{{y:,.0f}}<br>Quarter: %{{x}}<extra></extra>'
))
# Calculate YoY growth for annotation
if not previous_year_data.empty:
current_total = current_year_data[selected_metric].sum()
previous_total = previous_year_data[selected_metric].sum()
growth = ((current_total - previous_total) / previous_total) * 100
fig.add_annotation(
text=f'YoY Growth: {growth:.1f}%',
xref='paper', yref='paper',
x=0.02, y=0.98,
showarrow=False,
font=dict(size=14, color=colors['accent']),
bgcolor='rgba(255,255,255,0.8)',
bordercolor=colors['accent'],
borderwidth=2
)
fig.update_layout(
template='plotly_white',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
font=dict(color=colors['text'], family='Segoe UI, Roboto'),
xaxis=dict(gridcolor=colors['grid'], title='Quarter'),
yaxis=dict(gridcolor=colors['grid'], title=selected_metric),
hovermode='x unified',
legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1),
margin=dict(l=60, r=30, t=50, b=50)
)
return fig
@callback(
Output('annual-bar-chart', 'figure'),
[Input('metric-filter', 'value')]
)
def update_annual_bar_chart(selected_metric):
"""Update annual bar chart comparing revenue and expenses"""
fig = go.Figure()
# Revenue bars
fig.add_trace(go.Bar(
x=annual_df['Year'],
y=annual_df['Revenue'],
name='Revenue',
marker_color=colors['primary'],
hovertemplate='Revenue: %{y:,.0f}<extra></extra>'
))
# Expenses bars
fig.add_trace(go.Bar(
x=annual_df['Year'],
y=annual_df['Expenses'],
name='Expenses',
marker_color=colors['accent'],
hovertemplate='Expenses: %{y:,.0f}<extra></extra>'
))
# Add profit line overlay
fig.add_trace(go.Scatter(
x=annual_df['Year'],
y=annual_df['Profit'],
name='Profit',
mode='lines+markers',
line=dict(color=colors['secondary'], width=3),
marker=dict(size=10),
yaxis='y2',
hovertemplate='Profit: %{y:,.0f}<extra></extra>'
))
fig.update_layout(
template='plotly_white',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
font=dict(color=colors['text'], family='Segoe UI, Roboto'),
barmode='group',
xaxis=dict(gridcolor=colors['grid'], title='Year'),
yaxis=dict(gridcolor=colors['grid'], title='Amount ($)'),
yaxis2=dict(
title='Profit ($)',
overlaying='y',
side='right',
showgrid=False
),
hovermode='x unified',
legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1),
margin=dict(l=60, r=60, t=50, b=50)
)
return fig
@callback(
Output('profit-margin-chart', 'figure'),
[Input('year-filter', 'value')]
)
def update_profit_margin_chart(selected_year):
"""Update profit margin evolution chart"""
# Filter data up to selected year
filtered_df = annual_df[annual_df['Year'] <= selected_year]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=filtered_df['Year'],
y=filtered_df['Profit_Margin'],
mode='lines+markers',
name='Profit Margin',
line=dict(color=colors['primary'], width=3),
marker=dict(size=12, color=colors['primary']),
fill='tozeroy',
fillcolor='rgba(52, 152, 219, 0.2)',
hovertemplate='Year: %{x}<br>Profit Margin: %{y:.1f}%<extra></extra>'
))
# Add average line
avg_margin = filtered_df['Profit_Margin'].mean()
fig.add_hline(
y=avg_margin,
line_dash="dash",
line_color=colors['accent'],
annotation_text=f'Average: {avg_margin:.1f}%',
annotation_position="top right"
)
fig.update_layout(
template='plotly_white',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
font=dict(color=colors['text'], family='Segoe UI, Roboto'),
xaxis=dict(gridcolor=colors['grid'], title='Year', dtick=1),
yaxis=dict(gridcolor=colors['grid'], title='Profit Margin (%)', ticksuffix='%'),
hovermode='x',
showlegend=False,
margin=dict(l=60, r=30, t=50, b=50)
)
return fig
@callback(
Output('customer-growth-chart', 'figure'),
[Input('year-filter', 'value')]
)
def update_customer_growth_chart(selected_year):
"""Update customer growth area chart"""
# Filter data up to selected year
filtered_df = annual_df[annual_df['Year'] <= selected_year]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=filtered_df['Year'],
y=filtered_df['Customers'],
mode='lines+markers',
name='Customers',
line=dict(color=colors['secondary'], width=3),
marker=dict(size=12, color=colors['secondary']),
fill='tozeroy',
fillcolor='rgba(46, 204, 113, 0.2)',
hovertemplate='Year: %{x}<br>Customers: %{y:,.0f}<extra></extra>'
))
# Add growth rate as secondary axis
growth_rate = filtered_df['Customers'].pct_change() * 100
fig.add_trace(go.Scatter(
x=filtered_df['Year'],
y=growth_rate,
name='Growth Rate',
mode='lines',
line=dict(color=colors['accent'], width=2, dash='dot'),
yaxis='y2',
hovertemplate='Year: %{x}<br>Growth: %{y:.1f}%<extra></extra>'
))
fig.update_layout(
template='plotly_white',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
font=dict(color=colors['text'], family='Segoe UI, Roboto'),
xaxis=dict(gridcolor=colors['grid'], title='Year', dtick=1),
yaxis=dict(gridcolor=colors['grid'], title='Number of Customers'),
yaxis2=dict(
title='Growth Rate (%)',
overlaying='y',
side='right',
showgrid=False,
ticksuffix='%'
),
hovermode='x unified',
legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1),
margin=dict(l=60, r=60, t=50, b=50)
)
return fig
@callback(
Output('market-share-chart', 'figure'),
[Input('year-filter', 'value')]
)
def update_market_share_chart(selected_year):
"""Update market share pie chart"""
# Get data for selected year
year_data = annual_df[annual_df['Year'] == selected_year]
if year_data.empty:
return go.Figure()
market_share = year_data['MarketShare'].iloc[0]
competitors_share = 100 - market_share
fig = go.Figure(data=[go.Pie(
labels=['Our Company', 'Competitors'],
values=[market_share, competitors_share],
hole=0.4,
marker=dict(colors=[colors['primary'], '#BDC3C7']),
textinfo='label+percent',
hovertemplate='%{label}: %{value:.1f}%<extra></extra>'
)])
fig.update_layout(
template='plotly_white',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
font=dict(color=colors['text'], family='Segoe UI, Roboto'),
annotations=[dict(
text=f'{selected_year}',
x=0.5, y=0.5,
font_size=20,
showarrow=False
)],
showlegend=True,
legend=dict(orientation='h', yanchor='bottom', y=-0.2),
margin=dict(l=30, r=30, t=50, b=50)
)
return fig
# ==============================================================================
# MAIN EXECUTION
# ==============================================================================
if __name__ == '__main__':
# For Replit compatibility
app.run(host='0.0.0.0', port=8080, debug=False)
Melde dich an, um den vollständigen Prompt zu sehen
Weiter mit:
Mit der Anmeldung akzeptierst du unsere Nutzungsbedingungen und Datenschutz
Verwendung
Dieser Prompt ist für die Verwendung mit coding gedacht. Kopiere den Inhalt oben und füge ihn in dein bevorzugtes KI-Tool ein.
Für beste Ergebnisse passe die Platzhalter (eckige Klammern oder Großbuchstaben) an deine Anforderungen an.
Referenzen
- Kategorie: coding-Prompts
- Quelle: https://x.com/itsPaulAi/status/1823414405876547803
Diskussion
0 Kommentare