Vai al contenuto

HTML_TAG_120_ __HTML_TAG_123_📄 Generare Plotly PDF Guide_HTML_TAG_124

Taglio di petto

Installazione

Tabella_127_

Comandi di base - Plotly Express (API di alto livello)

Tabella_128_

Comandi di base - Oggetti di grafico (API di basso livello)

Tabella_129_

Uso avanzato - Personalizzazione

Tabella_130_

Uso avanzato - Subplots and Multiple Axes

Tabella_131_

Uso avanzato - Annotazioni e forme

Tabella_132_

Configurazione - Opzioni di layout

# Complete layout configuration
fig.update_layout(
    title=dict(
        text='Chart Title',
        font=dict(size=24, color='navy'),
        x=0.5,  # Center title
        xanchor='center'
    ),
    xaxis=dict(
        title='X Axis Label',
        showgrid=True,
        gridcolor='lightgray',
        zeroline=True,
        showline=True,
        linecolor='black'
    ),
    yaxis=dict(
        title='Y Axis Label',
        showgrid=True,
        gridcolor='lightgray',
        range=[0, 100]  # Fixed range
    ),
    plot_bgcolor='rgba(0,0,0,0)',  # Transparent background
    paper_bgcolor='white',
    font=dict(family='Arial', size=12, color='black'),
    showlegend=True,
    legend=dict(
        x=1,
        y=1,
        xanchor='right',
        yanchor='top',
        bgcolor='rgba(255,255,255,0.5)'
    ),
    hovermode='closest',  # or 'x', 'y', 'x unified'
    width=800,
    height=600,
    margin=dict(l=50, r=50, t=50, b=50)
)

Configuration - Trace Styling

# Scatter plot styling
fig.update_traces(
    marker=dict(
        size=10,
        color='blue',
        opacity=0.7,
        line=dict(width=2, color='darkblue'),
        symbol='circle'  # or 'square', 'diamond', 'cross', etc.
    ),
    line=dict(
        color='red',
        width=3,
        dash='dash'  # or 'dot', 'dashdot', 'solid'
    ),
    textposition='top center',
    textfont=dict(size=12, color='black')
)

# Bar chart styling
fig.update_traces(
    marker=dict(
        color='lightblue',
        line=dict(color='darkblue', width=1.5)
    ),
    texttemplate='%{y:.2f}',
    textposition='outside'
)

Configurazione - Impostazioni Renderer

import plotly.io as pio

# Set default renderer
pio.renderers.default = 'browser'  # or 'notebook', 'jupyterlab', 'vscode'

# Check available renderers
print(pio.renderers)

# Set default template
pio.templates.default = 'plotly_dark'

# Available templates: plotly, plotly_white, plotly_dark, ggplot2, 
# seaborn, simple_white, none

Common Use Cases

Use Case 1: Time Series Analysis with Range Slider

import plotly.express as px
import pandas as pd

# Create time series data
df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=365),
    'value': np.random.randn(365).cumsum()
})

# Create interactive time series
fig = px.line(df, x='date', y='value', title='Time Series with Range Slider')

# Add range slider and buttons
fig.update_xaxes(
    rangeslider_visible=True,
    rangeselector=dict(
        buttons=list([
            dict(count=1, label="1m", step="month", stepmode="backward"),
            dict(count=6, label="6m", step="month", stepmode="backward"),
            dict(count=1, label="YTD", step="year", stepmode="todate"),
            dict(count=1, label="1y", step="year", stepmode="backward"),
            dict(step="all")
        ])
    )
)

fig.show()

Use Case 2: Multi-Metric Dashboard with Subplots

from plotly.subplots import make_subplots
import plotly.graph_objects as go

# Create subplot grid
fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=('Sales Trend', 'Category Distribution', 
                    'Regional Performance', 'Monthly Comparison'),
    specs=[[{'type': 'scatter'}, {'type': 'bar'}],
           [{'type': 'pie'}, {'type': 'box'}]]
)

# Add line chart
fig.add_trace(
    go.Scatter(x=[1,2,3,4], y=[10,15,13,17], mode='lines+markers', name='Sales'),
    row=1, col=1
)

# Add bar chart
fig.add_trace(
    go.Bar(x=['A','B','C'], y=[20,30,25], name='Categories'),
    row=1, col=2
)

# Add pie chart
fig.add_trace(
    go.Pie(labels=['East','West','North','South'], values=[30,25,20,25]),
    row=2, col=1
)

# Add box plot
fig.add_trace(
    go.Box(y=[10,12,15,18,20,22,25,28,30], name='Distribution'),
    row=2, col=2
)

fig.update_layout(height=800, showlegend=False, title_text='Business Dashboard')
fig.show()

Use Case 3: Correlation Heatmap with Annotations

import plotly.express as px
import pandas as pd
import numpy as np

# Create sample correlation matrix
df = pd.DataFrame(np.random.randn(100, 5), columns=['A', 'B', 'C', 'D', 'E'])
corr_matrix = df.corr()

# Create annotated heatmap
fig = px.imshow(
    corr_matrix,
    text_auto='.2f',  # Show values with 2 decimal places
    aspect='auto',
    color_continuous_scale='RdBu_r',  # Red-Blue reversed
    zmin=-1, zmax=1  # Correlation range
)

fig.update_layout(
    title='Correlation Matrix',
    xaxis_title='Variables',
    yaxis_title='Variables'
)

fig.show()

Use Case 4: Interactive 3D Scatter with Custom Hover

import plotly.express as px
import pandas as pd
import numpy as np

# Create 3D dataset
df = pd.DataFrame({
    'x': np.random.randn(200),
    'y': np.random.randn(200),
    'z': np.random.randn(200),
    'category': np.random.choice(['A', 'B', 'C'], 200),
    'size': np.random.randint(5, 30, 200),
    'label': [f'Point {i}' for i in range(200)]
})

# Create 3D scatter
fig = px.scatter_3d(
    df, x='x', y='y', z='z',
    color='category',
    size='size',
    hover_data=['label', 'size'],
    title='3D Scatter Plot with Categories'
)

# Customize 3D scene
fig.update_layout(
    scene=dict(
        xaxis_title='X Axis',
        yaxis_title='Y Axis',
        zaxis_title='Z Axis',
        camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
    )
)

fig.show()

Use Case 5: Animated Scatter Plot

import plotly.express as px

# Create data with time dimension
df = pd.DataFrame({
    'year': [2020]*5 + [2021]*5 + [2022]*5,
    'country': ['A', 'B', 'C', 'D', 'E'] * 3,
    'gdp': np.random.randint(1000, 5000, 15),
    'population': np.random.randint(10, 100, 15)
})

# Create animated scatter
fig = px.scatter(
    df, x='gdp', y='population',
    animation_frame='year',
    animation_group='country',
    size='population',
    color='country',
    hover_name='country',
    size_max=55,
    range_x=[0, 6000],
    range_y=[0, 120],
    title='GDP vs Population Over Time'
)

fig.update_layout(transition_duration=500)
fig.show()

Migliori Pratiche

  • Utilizzare Plotly Express per una rapida prototipazione: Iniziare con px_ per una rapida visualizzazione, quindi passare a go_ quando hai bisogno di un controllo accurato su ogni elemento
  • ** Modelli di levaggio per consistenza **: Impostare un modello predefinito con pio.templates.default per mantenere uno stile coerente in tutte le visualizzazioni del tuo progetto
  • Ottimizzare per grandi set di dati: Per i set di dati con punti >10k, prendere in considerazione l'utilizzo __INLINE_CODE_91_ invece di scatter, o utilizzare datashader per la pre-aggregazione prima di tracciare
  • Configurare le visualizzazioni: Includere sempre le etichette degli assi, i titoli e le leggende. Utilizza palette colorblind-friendly come plotly.colors.qualitative.Safe
  • Esporta considerazioni**: Utilizzare kaleido per le esportazioni statiche di alta qualità. Per l'integrazione web, utilizzare fig.write_html(include_plotlyjs='cdn') per ridurre la dimensione del file
  • ** Caratteristiche interattive**: Abilita hovermode='x unified' per serie di tempo per confrontare più tracce contemporaneamente allo stesso valore x
  • ** Gestione della memoria ** Quando si creano più figure in loop, chiamare esplicitamente fig = None o utilizzare i responsabili contestuali per la memoria libera
  • ** Controllo della tensione ** Salvare le configurazioni delle figure come JSON con fig.to_json() per la riproducibilità e il controllo delle versioni delle visualizzazioni

Risoluzione dei problemi

TABLE_133_| Stile inconsistente tra le figure | Set default template all'inizio: pio.templates.default = 'plotly_white' e utilizzare fig.update_layout(template='plotly_white') |