Plotly Python Library

repository·main·Indexed 12 days ago

https://github.com/plotly/plotly.py

An open-source interactive, browser-based data visualization library for Python. Version 6.9.0 provides a declarative interface for over 30 chart types, including scientific, 3D, statistical, and geographic visualizations. It features Plotly Express for rapid charting, Graph Objects for granular control, and Figure Factories for complex visualizations.

Tokens
324.1K
Snippets
898
Records
1K
Agent score
89%

What's inside Plotly

  1. Overview of Plotly Express (PX)

    main

    Plotly Express (plotly.express, commonly imported as px) is a high-level, terse, and consistent API for creating figures. It is the recommended starting point for most common visualizations.

    Key characteristics:

    • Single Function Calls: Most figures can be created with a single function call.
    • Graph Objects Integration: Every PX function returns a plotly.graph_objects.Figure instance, allowing you to use standard methods like .update_layout() or .add_trace() for fine-grained customization.
    • Consistent API: The design allows for easy switching between different chart types (e.g., from scatter to bar) during data exploration.
    • Built-in Resources: Access demo datasets via px.data and color scales/sequences via px.colors.
    import plotly.express as px
    
    # Example: Basic scatter plot using built-in data
    df = px.data.iris()
    fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
    fig.show()
  2. Use plotly.figure_factory for complex chart generation

    main

    plotly.figure_factory is a module containing helper methods designed to simplify the creation of complex, specialized charts that would otherwise require manual construction of many traces and layouts. Instead of building every component from scratch, you can call a single factory function to generate a complete plotly.graph_objects.Figure object.

    Available helper methods include:

    • Density & Heatmaps: create_2d_density, create_annotated_heatmap, create_hexbin_map
    • Statistical & Distribution: create_distplot, create_violin, create_dendrogram
    • Financial: create_candlestick, create_ohlc
    • Geospatial: create_choropleth, create_hexbin_map
    • Scientific & Specialized: create_quiver, create_streamline, create_trisurf, create_ternary_contour, create_scatterplotmatrix
    • Project Management & Data: create_gantt, create_bullet, create_table, create_facet_grid
  3. Use plotly.io for low-level figure operations

    main
    The plotly.io module provides a low-level interface for displaying, reading, and writing Plotly figures. It is the primary interface for converting figures to different formats (HTML, JSON, Images) and managing how they are rendered in various environments.
  4. Use plotly.express for rapid figure generation

    main

    The plotly.express module (commonly imported as px) provides a high-level API designed for rapid data visualization. It allows you to create complex figures with minimal code by passing data structures (like Pandas DataFrames) directly into specialized functions.

    Commonly used functions include:

    • Scatter plots: scatter, scatter_3d, scatter_polar, scatter_ternary, scatter_map, scatter_mapbox, scatter_geo
    • Line plots: line, line_3d, line_polar, line_ternary, line_map, line_mapbox, line_geo
    • Statistical charts: bar, violin, box, ecdf, strip, histogram, area
    • Distribution/Density: density_contour, density_heatmap, density_map, density_mapbox
    • Hierarchical/Part-to-whole: pie, treemap, sunburst, icicle, funnel, funnel_area
    • Specialized: imshow (for images), scatter_matrix, parallel_coordinates, parallel_categories, choropleth (for maps)
    import plotly.express as px
  5. Explore the plotly.py submodules

    main

    The plotly package is organized into several specialized submodules depending on your visualization needs:

    • Plotly Express (px): The high-level interface designed for rapid data visualization with minimal code.
    • Graph Objects (go): The low-level interface providing granular control over figures, traces, and layouts.
    • Subplots: Helper functions used to layout multi-plot figures within a single figure.
    • Figure Factories (ff): Helper methods for building specific, complex chart types automatically.
    • I/O: The low-level interface for displaying, reading, and writing figure files.
    • plotly.colors: Provides colorscales and various color utility functions.
    • plotly.data: Contains built-in datasets used for demonstration, education, and testing.
  6. What is a Figure Factory in Plotly?

    main

    In the Plotly Python library, there is a distinction between basic plot types and Figure Factories:

    1. Basic Plot Types: Created using the plotly.graph_objs module (e.g., go.Scatter, go.Box, go.Bar). These are the fundamental building blocks of all Plotly charts.
    2. Figure Factories: High-level wrappers that utilize plotly.graph_objs to build complex charts. They automate the process of creating multiple traces and layouts required for sophisticated visualizations.

    For example, a Scatterplot Matrix is a figure factory because it internally utilizes go.Scatter, go.Box, and go.Histogram to construct a single complex visualization.

  7. Understand Long, Wide, and Mixed-form data in Plotly Express

    main

    Plotly Express functions handle different data organizational conventions:

    • Long-form data (Tidy): One row per observation, one column per variable. Most px functions work with this format.
    • Wide-form data: One row per value of one variable, with columns representing values of another variable. This is suitable for 2D data. Specific 2D-Cartesian functions like px.scatter, px.line, px.bar, px.histogram, px.violin, px.box, px.strip, px.funnel, px.density_heatmap, and px.density_contour support this.
    • Mixed-form data: A hybrid of long and wide forms.

    Note: px.imshow only operates on wide-form input.

    When using wide-form data, axis and legend labels might default to generic names like "value" or "variable". You can override these using the labels argument.

    import plotly.express as px
    
    # Long-form example
    long_df = px.data.medals_long()
    fig_long = px.bar(long_df, x="nation", y="count", color="medal")
    
    # Wide-form example
    wide_df = px.data.medals_wide()
    fig_wide = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"])
    
    # Relabeling wide-form labels
    fig_relabelled = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"],
                            labels={"value": "count", "variable": "medal"})
  8. Use built-in sequential color scales

    main

    Sequential color scales are appropriate for most continuous data. They are located in the plotly.colors.sequential module. You can visualize all available sequential scales using the swatches_continuous() method.

    import plotly.express as px
    
    fig = px.colors.sequential.swatches_continuous()
    fig.show()
  9. Control Legend Order and Ranking

    main

    Legend order can be managed in several ways:

    1. Plotly Express: Use category_orders to define the order of categorical axes and legend items.
    2. Stacked Bars: When using barmode="stack", you can set layout.legend.traceorder="reversed" to align the legend order with the stacking order.
    3. Graph Objects: Items appear in the order traces are added to the data array.
    4. Legend Rank: Use the legendrank attribute on traces or shapes to explicitly set their position. Lower ranks appear first (at the top). The default rank is 1000.
    5. Pie Traces: For pie traces, legendrank accepts an array to rank individual slices independently.
    6. Shapes: Shapes with showlegend=True appear after all traces by default, but can be moved using legendrank.
    import plotly.graph_objects as go
    
    # Using legendrank to control order
    fig = go.Figure()
    fig.add_trace(go.Bar(name="fourth", x=["a", "b"], y=[2,1], legendrank=5))
    fig.add_trace(go.Bar(name="second", x=["a", "b"], y=[2,1], legendrank=4))
    fig.add_trace(go.Bar(name="first", x=["a", "b"], y=[1,2], legendrank=2))
    fig.add_trace(go.Bar(name="third", x=["a", "b"], y=[1,2], legendrank=3))
    fig.add_shape(
        legendrank=1,
        showlegend=True,
        type="line",
        xref="paper",
        line=dict(dash="5px"),
        x0=0.05,
        x1=0.45,
        y0=1.5,
        y1=1.5,
    )
    fig.show()
  10. Create Animation Frames

    main

    An animation is composed of a list of frames. Each frame is a dictionary containing the data to be displayed at that specific point in time and a name to identify the frame.

    Structure:

    frame = {'data': [data_dict_1, data_dict_2, ...], 'name': 'frame_name'}

    When creating frames for a slider, ensure the name of the frame matches the value or label logic used in your slider steps so the slider can trigger the correct frame.