Use codebase.visualize(fig) to view Plotly charts in the Codegen IDE

Plotly Customization

Plotly offers a wide range of customization options to create professional and interactive data visualizations. This guide will walk you through some of the key features for enhancing your charts.

Layout Customization

Title and Axes

Customize the overall layout of your chart, including titles, axes labels, and font styles:

fig.update_layout(
    title="My Custom Chart",
    title_font=dict(size=24, color="darkblue", family="Arial"),
    xaxis_title="X-Axis Label",
    yaxis_title="Y-Axis Label",
    font=dict(size=14, family="Arial")
)

Margins and Sizing

Adjust the margins and overall size of your plot:

fig.update_layout(
    width=800,
    height=600,
    margin=dict(l=50, r=50, t=80, b=50)
)

Background and Grid

Modify the plot background, grid lines, and zero lines:

fig.update_layout(
    plot_bgcolor="lightgray",
    paper_bgcolor="white",
    xaxis=dict(showgrid=True, gridcolor="lightgray", zeroline=True, zerolinecolor="black"),
    yaxis=dict(showgrid=True, gridcolor="lightgray", zeroline=True, zerolinecolor="black")
)

Trace Customization

Colors and Styles

Customize the appearance of individual traces:

fig.update_traces(
    marker=dict(color="royalblue", size=10, line=dict(color="darkblue", width=2)),
    line=dict(color="firebrick", width=3, dash="dot"),
    opacity=0.8
)

Hover Information

Enhance the hover information displayed when interacting with data points:

fig.update_traces(
    hoverinfo="text+x+y",
    hovertext=["Custom hover text 1", "Custom hover text 2", "Custom hover text 3"],
    hoverlabel=dict(bgcolor="white", font_size=12, font_family="Rockwell")
)

Advanced Customization

Subplots

Create multi-plot layouts using make_subplots:

from plotly.subplots import make_subplots

fig = make_subplots(rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

# Add traces to subplots
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Bar(x=[1, 2, 3], y=[2, 3, 1]), row=1, col=2)
fig.add_trace(go.Heatmap(z=[[1, 2], [3, 4]]), row=2, col=1)
fig.add_trace(go.Box(y=[1, 2, 3, 4, 5]), row=2, col=2)

fig.update_layout(height=800, width=800, title_text="Subplot Example")

Animations

Create animated charts using frames:

import plotly.graph_objects as go

# Create frames for animation
frames = [go.Frame(data=[go.Scatter(x=[1, 2], y=[i, i**2])]) for i in range(10)]

fig = go.Figure(
    data=[go.Scatter(x=[1, 2], y=[0, 0])],
    layout=go.Layout(
        title="Simple Animation",
        xaxis=dict(range=[0, 3], autorange=False),
        yaxis=dict(range=[0, 20], autorange=False),
        updatemenus=[dict(
            type="buttons",
            buttons=[dict(label="Play", method="animate", args=[None])]
        )]
    ),
    frames=frames
)

Custom Shapes and Annotations

Add shapes and annotations to your plots:

fig.update_layout(
    shapes=[
        dict(
            type="rect",
            xref="x", yref="y",
            x0=1, y0=1, x1=2, y1=3,
            line=dict(color="red", width=2),
            fillcolor="rgba(255, 0, 0, 0.2)",
        ),
    ],
    annotations=[
        dict(
            x=2.5, y=4,
            xref="x", yref="y",
            text="Important Point",
            showarrow=True,
            arrowhead=2,
            arrowsize=1,
            arrowwidth=2,
            arrowcolor="black",
        )
    ]
)

Interactivity

Zoom and Pan

Enable or disable zoom and pan functionality:

fig.update_layout(
    xaxis=dict(fixedrange=False),  # Enable x-axis zoom
    yaxis=dict(fixedrange=True),   # Disable y-axis zoom
    dragmode="pan"  # Set default drag mode to pan
)

Click Events

Capture click events on your chart (requires additional JavaScript):

fig.update_layout(
    clickmode="event+select"
)

Customizable Buttons

Add custom buttons for interactivity:

fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            direction="left",
            buttons=[
                dict(label="Linear Scale", method="relayout", args=["yaxis.type", "linear"]),
                dict(label="Log Scale", method="relayout", args=["yaxis.type", "log"]),
            ],
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.1,
            xanchor="left",
            y=1.1,
            yanchor="top"
        ),
    ]
)

Theming

Built-in Themes

Apply pre-defined themes to your charts:

import plotly.io as pio

pio.templates.default = "plotly_dark"  # Set default theme
# Other options: "plotly", "plotly_white", "simple_white", "ggplot2", "seaborn", "none"

# Or apply theme to a specific figure
fig.update_layout(template="seaborn")

Custom Themes

Create and apply custom themes:

import plotly.graph_objects as go
import plotly.io as pio

my_theme = go.layout.Template(
    layout=go.Layout(
        font=dict(family="Arial", size=14),
        title=dict(font=dict(size=24, color="darkblue")),
        plot_bgcolor="lightgray",
        paper_bgcolor="white",
        colorway=["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"],
    )
)

pio.templates["my_custom_theme"] = my_theme
fig.update_layout(template="my_custom_theme")

Performance Optimization

For large datasets, consider using these optimization techniques:

  • Use Scattergl instead of Scatter for improved rendering of many points.
  • Implement data decimation to reduce the number of points plotted.
  • Use webgl rendering for 3D plots.
import plotly.graph_objects as go

# Example of using Scattergl for better performance
fig = go.Figure(data=go.Scattergl(x=large_x_data, y=large_y_data, mode='markers'))

By leveraging these customization options, you can create highly tailored, interactive, and visually appealing charts with Plotly. Experiment with different combinations to find the perfect style for your data visualization needs.