Zum Inhalt

_

_ _

_

Plotly Cheatsheet

• Installation

Platform/Method Command
Python (pip) INLINE_CODE_8
Python with all dependencies INLINE_CODE_9
Conda (recommended) INLINE_CODE_10
Jupyter Notebook support INLINE_CODE_11
JupyterLab 3.x INLINE_CODE_12
Dash framework INLINE_CODE_13
Static image export INLINE_CODE_14
Development version INLINE_CODE_15
Upgrade to latest INLINE_CODE_16
Verify installation INLINE_CODE_17

oder Grundlegende Befehle - Plotly Express (High-Level API)

Command Description
INLINE_CODE_18 Import Plotly Express for quick visualizations
INLINE_CODE_19 Create scatter plot from DataFrame
INLINE_CODE_20 Create line chart for time series
INLINE_CODE_21 Create vertical bar chart
INLINE_CODE_22 Create horizontal bar chart
INLINE_CODE_23 Create histogram with specified bins
INLINE_CODE_24 Create box plot for distribution analysis
INLINE_CODE_25 Create violin plot showing distribution
INLINE_CODE_26 Create pie chart
INLINE_CODE_27 Create donut chart
INLINE_CODE_28 Create 3D scatter plot
INLINE_CODE_29 Create heatmap from 2D array
INLINE_CODE_30 Create density heatmap from data points
INLINE_CODE_31 Create area chart
INLINE_CODE_32 Create funnel chart for conversion analysis
INLINE_CODE_33 Display figure in default renderer
INLINE_CODE_34 Display figure in web browser
INLINE_CODE_35 Save figure as HTML file
INLINE_CODE_36 Save figure as PNG image
INLINE_CODE_37 Save figure as PDF

oder Grundlegende Befehle - Graph Objekte (Low-Level API)

Command Description
INLINE_CODE_38 Import Graph Objects for detailed control
INLINE_CODE_39 Create empty figure object
INLINE_CODE_40 Create scatter trace
INLINE_CODE_41 Create line trace
INLINE_CODE_42 Create markers-only scatter
INLINE_CODE_43 Create line with markers
INLINE_CODE_44 Create bar trace
INLINE_CODE_45 Create histogram trace
INLINE_CODE_46 Create box plot trace
INLINE_CODE_47 Create heatmap trace
INLINE_CODE_48 Create 3D scatter trace
INLINE_CODE_49 Create 3D surface plot
INLINE_CODE_50 Create contour plot
INLINE_CODE_51 Add trace to existing figure
INLINE_CODE_52 Access all traces in figure
INLINE_CODE_53 Access figure layout properties
_
Erweiterte Nutzung - Anpassung
Command Description
INLINE_CODE_54 Update figure title
INLINE_CODE_55 Apply dark theme template
INLINE_CODE_56 Set figure dimensions
INLINE_CODE_57 Update x-axis properties
INLINE_CODE_58 Update y-axis with log scale
INLINE_CODE_59 Update all trace properties
INLINE_CODE_60 Update specific trace by name
INLINE_CODE_61 Color points by categorical variable
INLINE_CODE_62 Size points by numerical variable
INLINE_CODE_63 Add custom hover information
INLINE_CODE_64 Create small multiples by column
INLINE_CODE_65 Create 2D grid of subplots
INLINE_CODE_66 Add ordinary least squares trendline
INLINE_CODE_67 Add marginal histogram on x-axis
INLINE_CODE_68 Set continuous color scale
_
Erweiterte Nutzung - Subplots und Multiple Axes
Command Description
INLINE_CODE_69 Import subplot functionality
INLINE_CODE_70 Create 2x2 subplot grid
INLINE_CODE_71 Create figure with secondary y-axis
INLINE_CODE_72 Add trace to specific subplot
INLINE_CODE_73 Create subplots with titles
INLINE_CODE_74 Create subplots sharing x-axis
INLINE_CODE_75 Set vertical spacing between subplots
INLINE_CODE_76 Synchronize x-axes across subplots
INLINE_CODE_77 Update primary y-axis
INLINE_CODE_78 Update secondary y-axis
_
Erweiterte Nutzung - Annotationen und Formen
Command Description
INLINE_CODE_79 Add text annotation at coordinates
INLINE_CODE_80 Add annotation with arrow
INLINE_CODE_81 Add rectangle shape
INLINE_CODE_82 Add line shape
INLINE_CODE_83 Add circle shape
INLINE_CODE_84 Add horizontal reference line
INLINE_CODE_85 Add vertical reference line
INLINE_CODE_86 Add horizontal rectangle region
INLINE_CODE_87 Add vertical rectangle region
_
Konfiguration - Layoutoptionen
# 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)
)

Konfiguration - 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'
)

Konfiguration - Renderer Einstellungen

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

Häufige Anwendungsfälle

Use Case 1: Zeitreihenanalyse mit 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 mit 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 mit 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()

oder Best Practices

  • ** Verwenden Sie Plotly Express für schnelle Prototyping*: Starten Sie mit px für schnelle Visualisierungen und wechseln Sie dann auf go (Graph Objects) wenn Sie eine feinkörnige Kontrolle über jedes Element benötigen
  • **Leverage Vorlagen für Konsistenz*: Legen Sie eine Standardvorlage mit pio.templates.default ein, um konsistentes Styling über alle Visualisierungen in Ihrem Projekt zu erhalten
  • **Optimieren für große Datensätze*: Bei Datensätzen mit >10k-Punkten sollten Sie statt scattergl__scatter_ verwenden oder datashader_ für die Voraggregation vor dem Ploten verwenden
  • **Make Visualisierungen zugänglich*: Immer gehören Achsenbeschriftungen, Titel und Legenden. Benutzen Sie farbenfrohe Paletten wie plotly.colors.qualitative.Safe
  • **Aussichten*: Verwenden Sie kaleido für hochwertige statische Exporte. Verwenden Sie fig.write_html(include_plotlyjs='cdn'), um die Dateigröße zu reduzieren
  • Interaktive Features: Aktivieren hovermode='x unified' für Zeitreihen, um mehrere Spuren gleichzeitig mit dem x-Wert zu vergleichen
  • Memory Management: Bei der Erstellung mehrerer Zahlen in Schleifen rufen Sie explizit fig = None an oder verwenden Sie Kontextmanager zum freien Speicher
  • **Versionskontrolle*: Speichern Sie Figurenkonfigurationen als JSON mit fig.to_json() für Reproduzierbarkeit und Versionskontrolle von Visualisierungen

Fehlerbehebung

Issue Solution
Figure not displaying in Jupyter Install widgets: INLINE_CODE_100 and restart kernel. Check renderer: INLINE_CODE_101
"No module named 'plotly'" error Install plotly: INLINE_CODE_102. If using conda, try: INLINE_CODE_103
Static image export fails Install kaleido: INLINE_CODE_104. For older systems, try: INLINE_CODE_105
Slow rendering with large datasets Switch to WebGL: use INLINE_CODE_106 instead of INLINE_CODE_107, or downsample data before plotting
Figures too small in output Set dimensions explicitly: INLINE_CODE_108 or use INLINE_CODE_109
Legend overlapping plot area Reposition legend: INLINE_CODE_110 or set INLINE_CODE_111
Hover labels cut off Increase margins: INLINE_CODE_112
Colors not showing correctly Ensure color column is correct type. For categorical: convert to string. For continuous: ensure numeric values
Animation not working Verify INLINE_CODE_113 column exists and has multiple unique values. Check data is sorted by animation frame
PDF export has missing elements Use SVG as intermediate: INLINE_CODE_114 then convert to PDF, or use INLINE_CODE_115
Memory error with subplots Create subplots incrementally, clearing unused figures. Use INLINE_CODE_116 and garbage collection: INLINE_CODE_117
Inkonsistentes Styling über Figuren Standardvorlage zu Beginn festlegen: __INLINE_CODE_118_ und verwenden fig.update_layout(template='plotly_white')