Traducción al español.
De Wikiprompt, la enciclopedia libre de prompts
Traducción al español. Un prompt para generar un script de Python usando Plotly Dash para crear un dashboard interactivo a partir de un PDF o archivo de datos, con gráficos, filtros y características dinámicas.
Contenido del PromptGuardar
🌐
"""
Interactive Dashboard for Key Figures Evolution
Author: Python Developer
Description: A modern, interactive dashboard built with Plotly Dash to visualize
key figures from a PDF document, with year filters, hover effects, and interactive legends.
Compatible with Replit environment.
"""
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 based on typical PDF report figures
# In production, replace this with actual data extraction from the PDF
np.random.seed(42)
years = list(range(2018, 2024))
# Revenue data (in millions)
revenue = [120, 145, 168, 192, 215, 238]
revenue_prev = [110, 120, 145, 168, 192, 215] # Previous period comparison
# Profit margins (%)
profit_margin = [15.2, 16.8, 17.5, 18.2, 19.1, 20.3]
profit_margin_prev = [14.1, 15.2, 16.8, 17.5, 18.2, 19.1]
# Customer acquisition (thousands)
customers = [45, 52, 61, 68, 75, 82]
customers_prev = [38, 45, 52, 61, 68, 75]
# Operational costs (millions)
op_costs = [85, 98, 112, 125, 138, 150]
op_costs_prev = [78, 85, 98, 112, 125, 138]
# Market share (%)
market_share = [12.5, 13.8, 15.2, 16.1, 17.3, 18.5]
market_share_prev = [11.2, 12.5, 13.8, 15.2, 16.1, 17.3]
# Create DataFrame
df = pd.DataFrame({
'Year': years,
'Revenue': revenue,
'Revenue_Prev': revenue_prev,
'Profit_Margin': profit_margin,
'Profit_Margin_Prev': profit_margin_prev,
'Customers': customers,
'Customers_Prev': customers_prev,
'Op_Costs': op_costs,
'Op_Costs_Prev': op_costs_prev,
'Market_Share': market_share,
'Market_Share_Prev': market_share_prev
})
# =============================================================================
# DASHBOARD INITIALIZATION
# =============================================================================
app = dash.Dash(__name__)
server = app.server # For Replit compatibility
# Modern color palette
colors = {
'background': '#FFFFFF',
'text': '#2C3E50',
'primary': '#3498DB',
'secondary': '#E74C3C',
'accent': '#2ECC71',
'grid': '#ECF0F1'
}
# =============================================================================
# LAYOUT
# =============================================================================
app.layout = html.Div(
style={
'backgroundColor': colors['background'],
'fontFamily': 'Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif',
'padding': '20px',
'maxWidth': '1200px',
'margin': '0 auto'
},
children=[
# Header Section
html.Div([
html.H1(
'Key Performance Indicators Dashboard',
style={
'color': colors['text'],
'textAlign': 'center',
'marginBottom': '5px',
'fontWeight': '300',
'fontSize': '2.5em'
}
),
html.P(
'Interactive visualization of company performance metrics',
style={
'color': colors['text'],
'textAlign': 'center',
'opacity': '0.7',
'fontSize': '1.1em',
'marginTop': '0'
}
),
html.Hr(style={'borderColor': colors['grid']})
]),
# Filters Section
html.Div([
html.Label(
'Select Year Range:',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.RangeSlider(
id='year-slider',
min=min(years),
max=max(years),
value=[min(years), max(years)],
marks={str(year): str(year) for year in years},
step=1,
tooltip={"placement": "bottom", "always_visible": True},
allowCross=False
)
], style={'marginBottom': '30px', 'padding': '10px'}),
# Chart 1: Revenue Evolution
html.Div([
html.H3(
'Revenue Evolution (in millions)',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.Graph(id='revenue-chart')
], style={'marginBottom': '40px'}),
# Chart 2: Profit Margin
html.Div([
html.H3(
'Profit Margin (%)',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.Graph(id='margin-chart')
], style={'marginBottom': '40px'}),
# Chart 3: Customer Acquisition
html.Div([
html.H3(
'Customer Acquisition (thousands)',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.Graph(id='customer-chart')
], style={'marginBottom': '40px'}),
# Chart 4: Operational Costs
html.Div([
html.H3(
'Operational Costs (in millions)',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.Graph(id='cost-chart')
], style={'marginBottom': '40px'}),
# Chart 5: Market Share
html.Div([
html.H3(
'Market Share (%)',
style={'color': colors['text'], 'fontWeight': '500'}
),
dcc.Graph(id='market-chart')
], style={'marginBottom': '40px'}),
# Footer
html.Footer(
'Data source: Company Annual Report | Generated: ' + datetime.now().strftime('%B %Y'),
style={
'textAlign': 'center',
'color': colors['text'],
'opacity': '0.6',
'marginTop': '30px',
'padding': '20px',
'borderTop': '1px solid ' + colors['grid']
}
)
]
)
# =============================================================================
# CALLBACKS AND CHART GENERATION
# =============================================================================
def create_comparison_chart(df_filtered, metric, metric_prev, title, yaxis_title):
"""
Helper function to create comparison charts with current vs previous period
Args:
df_filtered: Filtered DataFrame
metric: Current period column name
metric_prev: Previous period column name
title: Chart title
yaxis_title: Y-axis label
Returns:
plotly figure object
"""
fig = go.Figure()
# Current period line
fig.add_trace(go.Scatter(
x=df_filtered['Year'],
y=df_filtered[metric],
mode='lines+markers',
name='Current Period',
line=dict(color=colors['primary'], width=3),
marker=dict(size=10, color=colors['primary']),
hovertemplate='<b>Year:</b> %{x}<br><b>Value:</b> %{y:.2f}<extra></extra>'
))
# Previous period line
fig.add_trace(go.Scatter(
x=df_filtered['Year'],
y=df_filtered[metric_prev],
mode='lines+markers',
name='Previous Period',
line=dict(color=colors['secondary'], width=3, dash='dash'),
marker=dict(size=8, color=colors['secondary']),
hovertemplate='<b>Year:</b> %{x}<br><b>Value:</b> %{y:.2f}<extra></extra>'
))
# Calculate percentage change for annotations
if len(df_filtered) > 0:
change = ((df_filtered[metric].iloc[-1] - df_filtered[metric_prev].iloc[-1])
/ df_filtered[metric_prev].iloc[-1] * 100)
fig.add_annotation(
text=f'YoY Change: {change:.1f}%',
xref='paper', yref='paper',
x=0.02, y=0.98,
showarrow=False,
font=dict(size=12, color=colors['accent']),
bgcolor='rgba(255,255,255,0.8)',
bordercolor=colors['grid'],
borderwidth=1
)
# Styling
fig.update_layout(
template='plotly_white',
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),
xaxis=dict(
title='Year',
gridcolor=colors['grid'],
tickmode='linear',
tick0=min(years),
dtick=1
),
yaxis=dict(
title=yaxis_title,
gridcolor=colors['grid']
),
plot_bgcolor=colors['background'],
paper_bgcolor=colors['background'],
font=dict(color=colors['text'])
)
return fig
@callback(
[Output('revenue-chart', 'figure'),
Output('margin-chart', 'figure'),
Output('customer-chart', 'figure'),
Output('cost-chart', 'figure'),
Output('market-chart', 'figure')],
[Input('year-slider', 'value')]
)
def update_charts(year_range):
"""
Main callback to update all charts based on year filter
Args:
year_range: List of [start_year, end_year] from slider
Returns:
Updated figure objects for all charts
"""
# Filter data based on selected year range
start_year, end_year = year_range
df_filtered = df[(df['Year'] >= start_year) & (df['Year'] <= end_year)]
# Create all charts
revenue_fig = create_comparison_chart(
df_filtered, 'Revenue', 'Revenue_Prev',
'Revenue Evolution', 'Revenue (Millions $)'
)
margin_fig = create_comparison_chart(
df_filtered, 'Profit_Margin', 'Profit_Margin_Prev',
'Profit Margin', 'Margin (%)'
)
customer_fig = create_comparison_chart(
df_filtered, 'Customers', 'Customers_Prev',
'Customer Acquisition', 'Customers (Thousands)'
)
cost_fig = create_comparison_chart(
df_filtered, 'Op_Costs', 'Op_Costs_Prev',
'Operational Costs', 'Costs (Millions $)'
)
market_fig = create_comparison_chart(
df_filtered, 'Market_Share', 'Market_Share_Prev',
'Market Share', 'Market Share (%)'
)
return revenue_fig, margin_fig, customer_fig, cost_fig, market_fig
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == '__main__':
# For Replit compatibility, use 0.0.0.0 as host
app.run_server(host='0.0.0.0', port=8080, debug=True)
Iniciá sesión para ver el prompt completo
Continuar con:
Al iniciar sesión, aceptás nuestros Términos de uso y Política de privacidad
Uso
Este prompt está diseñado para usarse con coding. Copiá el contenido de arriba y pegalo en tu herramienta de IA preferida.
Para mejores resultados, personalizá los marcadores (indicados con corchetes o mayúsculas) con tus requisitos específicos.
Referencias
- Categoría: Prompts de coding
- Fuente: https://x.com/itsPaulAi/status/1823414405876547803
Discusión
0 comentarios