> Note: Dash.NET is currently considered experimental. If your organization is interested in sponsoring Dash.NET, please get in touch.

# DCC.Graph.graph

The `DCC.Graph.graph` component can be used to render any plotly-powered data visualization, passed as the `figure` argument.

## Primer on Plotly Graphing Library

- The Plotly Graphing Library, known as the library `plotly`, generates "figures". These are used in `DCC.Graph.graph` with e.g. `Graph.graph "graph-id" [ Graph.Attr.figure fig ]` with `fig` a plotly figure.

- To get started with plotly, learn how its documentation is organized:

  1. Learn the architecture of the `figure`: https://plotly.com/fsharp/creating-and-updating-figures/

  2. Every chart type has a set of examples at a unique URL. Familiarize yourself with the structure of these pages. Google is your friend. For example "Histograms in Fsharp" is documented at https://plotly.com/fsharp/histograms

  3. Plotly `GenericChart` is the recommended high-level interface. Understand where it fits in by reading 1. Once you understand its structure, you reed more here: https://plotly.net/

  4. Every aspect of a chart is configurable. Read through 1 to understand the low-level `figure` interface and how to modify the properties of a generated figure. Once you understand it, view all of the properties by visiting the "Figure Reference" page at https://plotly.com/fsharp/reference.

  5. If for some reason `GenericChart` does not meet your needs you can use the plotly `DynamicObj` or anonymouse types.

- Plotly supports 40-50 different chart types. Learn more by navigating https://plotly.com/fsharp/.
- In development, you can create figures by running Dash apps or in other environments like Jupyter, your console, and more.
- To see all of these rendering environments, see https://plotly.com/fsharp/renderers/

## Examples

### GenericChart in Dash

The `fig` object is passed directly into the `figure` property of `DCC.Graph.graph`:

    open Dash.NET.Giraffe

    open Dash.NET.DCC
    open Plotly.NET
    open Plotly.NET.LayoutObjects
    open FSharp.Data

    let [<Literal>] Csv = "https://raw.githubusercontent.com/plotly/datasets/master/iris.csv"
    type IrisData = CsvProvider<Csv>
    let iris = IrisData.Load(Csv).Cache()
    let h = iris.Rows |> Seq.head

    let fig =
        Chart.Scatter(
            (iris.Rows |> Seq.map (fun r -> r.SepalWidth)),
            (iris.Rows |> Seq.map (fun r -> r.SepalLength)),
            StyleParam.Mode.Markers
        )
        |> Chart.withXAxis(LinearAxis.init(Title=Title.init (Text=nameof(h.SepalWidth))))
        |> Chart.withYAxis(LinearAxis.init(Title=Title.init (Text=nameof(h.SepalLength))))
        |> GenericChart.toFigure

    let layout = Graph.graph "graph" [ Graph.Attr.figure fig ]

    [<EntryPoint>]
    let main argv =
        DashApp.initDefault()
        |> DashApp.withLayout layout
        |> DashApp.run argv (DashGiraffeConfig.initDefault "localhost")

### Using the Low-Level Interface with plotly `DynamicObj`

Using the Low-Level Interface with plotly `DynamicObj`

Read through (1) above to learn more about the difference between `GenericChart` & `DynamicObject`.

    open Dash.NET.Giraffe
    open Dash.NET.DCC
    open Plotly.NET

    let trace =
        let tmp = Trace("scatter")
        tmp?x <- [1;2;3]
        tmp?y <- [4;1;2]
        tmp

    let fig =
        GenericChart.Figure.create [ trace ] (Layout())
        |> GenericChart.fromFigure
        |> GenericChart.toFigure

    let layout = Graph.graph "graph" [ Graph.Attr.figure fig ]

    [<EntryPoint>]
    let main argv =
        DashApp.initDefault()
        |> DashApp.withLayout layout
        |> DashApp.run argv (DashGiraffeConfig.initDefault "localhost")

### Using the Low-Level Interface with Anonymous Records

    open Dash.NET.Giraffe
    open Dash.NET.DCC

    let layout =
        Graph.graph "graph" [
            Graph.Attr.figure
                {|
                    data = [
                        {| x = [1; 2; 3]; y = [4; 1; 2]; ``type`` = "bar"; name = "SF" |}
                        {| x = [1; 2; 3]; y = [2; 4; 5]; ``type`` = "bar"; name = "Montréal" |}
                    ]
                    layout = {| title = "Dash Data Visualization" |}
                |}
        ]

    [<EntryPoint>]
    let main argv =
        DashApp.initDefault()
        |> DashApp.withLayout layout
        |> DashApp.run argv (DashGiraffeConfig.initDefault "localhost")

## Interactive Graphing with Callbacks

Interactive Visualizations in the Dash Fundamentals explains how to capture user interaction events with a `DCC.Graph.graph`, and how to update the `figure` property in callbacks.

Some advanced features are documented in community forum posts:

- How to preserve the UI state (zoom level etc.) of a Graph when updating the Graph in a callback https://community.plot.ly/t/preserving-ui-state-like-zoom-in-dcc-graph-with-uirevision/15793
- Graph transitions for smooth transitions or animations on Graph updates https://community.plot.ly/t/exploring-a-transitions-api-for-dcc-graph/15468

Sign up for Dash Club → Two free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

## Controlling the Plotly.js Version Used by DCC.Graph.graph

The `DCC.Graph.graph` component leverages the Plotly.js library to render visualizations.

You can override the Plotly.js version by placing a Plotly.js bundle in the WebRoot directory.

This technique can be used to:

- take advantage of new features in a version of Plotly.js that is more recent than the one that is included in the currently installed version of Dash or Dash Design Kit.
- take advantage of more desirable behavior of a version of Plotly.js that is less recent than the one that is included in the currently installed version of Dash or Dash Design Kit. We strive to make Plotly.js releases completely backwards-compatible, so you shouldn't have to do this very often.
- use a Plotly-distributed Plotly.js partial bundle or a custom-built Plotly.js bundle which only includes the subset of Plotly.js features that your Dash app uses. Partial bundles are smaller than the full Plotly.js bundles that come with the `Graph` component and can therefore improve your app's loading time.

## LaTeX

`DCC.Graph.graph` supports rendering LaTeX on titles, labels, and annotations. It uses MathJax version 3.2 and can be enabled by setting `mathjax=True` on the component. Put content to be rendered with MathJax between `$` delimiters. If you need a literal `$`, use the HTML entity `&#36;`. To include text within MathJax delimiters, use `\text{<your_text_goes_here>}`. In the following example `(solar radius)` is included as text on the `yaxis_title`.

> This example has not been ported to F# yet - showing the Python version instead.

> Visit the old docs site for F# at: https://community.plotly.com/c/dash/net/26

    from dash import Dash, dcc, html
    import plotly.express as px

    fig = px.line(x=[1, 2, 3, 4], y=[1, 4, 9, 16], title=r'$\alpha_{1c} = 352 \pm 11 \text{ km s}^{-1}$')
    fig.update_layout(
        xaxis_title=r'$\sqrt{(n_\text{c}(t|{T_\text{early}}))}$',
        yaxis_title=r'$d, r \text{ (solar radius)}$'
    )

    app = Dash()

    app.layout = html.Div([

        dcc.Markdown('''
        ## LaTeX in a Markdown component:

        This example uses the block delimiter:
        $$
        \\frac{1}{(\\sqrt{\\phi \\sqrt{5}}-\\phi) e^{\\frac25 \\pi}} =
        1+\\frac{e^{-2\\pi}} {1+\\frac{e^{-4\\pi}} {1+\\frac{e^{-6\\pi}}
        {1+\\frac{e^{-8\\pi}} {1+\\ldots} } } }
        $$

        This example uses the inline delimiter:
        $E^2=m^2c^4+p^2c^2$

        ## LaTeX in a Graph component:

        ''', mathjax=True),

        dcc.Graph(mathjax=True, figure=fig)]
    )

    if __name__ == '__main__':
        app.run(debug=True)

> Rendering LaTeX is not currently supported on `hovertext`, `texttemplate`, `ticktext`, `text` on bar chart bars, or `labels` when displayed on pie charts. If you or your company would like to sponsor improvements to LaTeX rendering in Dash, get in touch with our advanced development team.

For an introduction to LaTeX math, see LaTeX/Mathematics.

## Graph Resizing and Responsiveness

There are quite a few options that you can take advantage of if you want the size of your graph to be reactive.

The default `plotly.js` behavior dictates that the graph should resize upon window resize. However, in some cases, you might want to resize the graph based on the size of its parent container instead. (You can set the size of the parent container with `StyleProperty ("height", height)` and `StyleProperty ("width", width)`.)

The `Responsive` property of the `DCC.Graph.graph` component allows you to define your desired behavior. In short, it accepts as a value `true`, `false`:

- `true` forces the graph to be responsive to window and parent resize, regardless of any other specifications in `Figure.Layout` or `Config`
- `false` forces the graph to be non-responsive to window and parent resize, regardless of any other specifications in `Figure.Layout` or `Config`

### How Resizing Works - Advanced

The properties of `DCC.Graph.graph` that can control the size of the graph (other than `Responsive`) are:

- `Chart.withLayout (Layout.init(Height = height))` - explicitly sets the height
- `Chart.withLayout (Layout.init(Width = width))`- explicitly sets the width
- `Chart.withLayout (Layout.init(AutoSize = true))`, sets the height and width of the graph to that of its parent container
- `Config.init(Responsive = true)`, changes the height and width of the graph upon window resize.

The `Responsive` property works in conjunction with the above properties in the following way:

- `true`: `Config?Responsive` and `Figure.Layout?AutoSize` are overridden with `true` values, and `Figure.Layout?Height` and `Figure.Layout?Width` are unset
- `false`: `Config?Responsive` and `Figure.Layout?AutoSize` are both overridden with `false` values

## Graph Properties

> Our recommended IDE for writing Dash apps is Dash Enterprise's Data Science Workspaces, which has typeahead support for Dash Component Properties. Find out if your company is using Dash Enterprise.

`id` (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across all of the components in an app.

`responsive` (a value equal to: true, false or 'auto'; default `'auto'`): If True, the Plotly.js plot will be fully responsive to window resize and parent element resize event. This is achieved by overriding `config.responsive` to True, `figure.layout.autosize` to True and unsetting `figure.layout.height` and `figure.layout.width`. If False, the Plotly.js plot not be responsive to window resize and parent element resize event. This is achieved by overriding `config.responsive` to False and `figure.layout.autosize` to False. If 'auto' (default), the Graph will determine if the Plotly.js plot can be made fully responsive (True) or not (False) based on the values in `config.responsive`, `figure.layout.autosize`, `figure.layout.height`, `figure.layout.width`. This is the legacy behavior of the Graph component. Needs to be combined with appropriate dimension / styling through the `style` prop to fully take effect.

`clickData` (record; optional): Data from latest click event. Read-only.

`clickAnnotationData` (record; optional): Data from latest click annotation event. Read-only.

`hoverData` (record; optional): Data from latest hover event. Read-only.

`clear_on_unhover` (bool; default `false`): If True, `clear_on_unhover` will clear the `hoverData` property when the user "unhovers" from a point. If False, then the `hoverData` property will be equal to the data from the last point that was hovered over.

`selectedData` (record; optional): Data from latest select event. Read-only.

`relayoutData` (record; optional): Data from latest relayout event which occurs when the user zooms or pans on the plot or other layout-level edits. Has the form `{<attr string>: <value>}` describing the changes made. Read-only.

`extendData` (list | record; optional): Data that should be appended to existing traces. Has the form `[updateData, traceIndices, maxPoints]`, where `updateData` is an object containing the data to extend, `traceIndices` (optional) is an array of trace indices that should be extended, and `maxPoints` (optional) is either an integer defining the maximum number of points allowed or an object with key:value pairs matching `updateData` Reference the Plotly.extendTraces API for full usage: https://plotly.com/javascript/plotlyjs-function-reference/#plotlyextendtraces.

`prependData` (list | record; optional): Data that should be prepended to existing traces. Has the form `[updateData, traceIndices, maxPoints]`, where `updateData` is an object containing the data to prepend, `traceIndices` (optional) is an array of trace indices that should be prepended, and `maxPoints` (optional) is either an integer defining the maximum number of points allowed or an object with key:value pairs matching `updateData` Reference the Plotly.prependTraces API for full usage: https://plotly.com/javascript/plotlyjs-function-reference/#plotlyprependtraces.

`restyleData` (list; optional): Data from latest restyle event which occurs when the user toggles a legend item, changes parcoords selections, or other trace-level edits. Has the form `[edits, indices]`, where `edits` is an object `{<attr string>: <value>}` describing the changes made, and `indices` is an array of trace indices that were edited. Read-only.

`figure` (record; default `{ data: [], layout: {}, frames: [],}`): Plotly `figure` object. See schema: https://plotly.com/javascript/reference `config` is set separately by the `config` property.

`figure` is a record with keys:

- `data` (list of records; optional)

- `frames` (list of records; optional)

- `layout` (record; optional)

`style` (record; optional): Generic style overrides on the plot div.

`className` (string; optional): className of the parent div.

`mathjax` (bool; default `false`): If true, loads mathjax v3 (tex-svg) into the page and use it in the graph.

`animate` (bool; default `false`): Beta: If true, animate between updates using plotly.js's `animate` function.

`animation_options` (record; default `{ frame: { redraw: false, }, transition: { duration: 750, ease: 'cubic-in-out', },}`): Beta: Object containing animation settings. Only applies if `animate` is `true`.

`config` (record; optional): Plotly.js config options. See https://plotly.com/javascript/configuration-options/ for more info.

`config` is a record with keys:

- `autosizable` (bool; optional): DO autosize once regardless of layout.autosize (use default width or height values otherwise).

- `displayModeBar` (a value equal to: true, false or 'hover'; optional): Display the mode bar (true, false, or 'hover').

- `displaylogo` (bool; optional): Add the plotly logo on the end of the mode bar.

- `doubleClick` (a value equal to: false, 'reset', 'autosize' or 'reset+autosize'; optional): Double click interaction (false, 'reset', 'autosize' or 'reset+autosize').

- `doubleClickDelay` (number; optional): Delay for registering a double-click event in ms. The minimum value is 100 and the maximum value is 1000. By default this is 300.

- `editSelection` (bool; optional): Enables moving selections.

- `editable` (bool; optional): We can edit titles, move annotations, etc - sets all pieces of `edits` unless a separate `edits` config item overrides individual parts.

- `edits` (record; optional): A set of editable properties.

  `edits` is a record with keys:

  - `annotationPosition` (bool; optional): The main anchor of the annotation, which is the text (if no arrow) or the arrow (which drags the whole thing leaving the arrow length & direction unchanged).

  - `annotationTail` (bool; optional): Just for annotations with arrows, change the length and direction of the arrow.

  - `annotationText` (bool; optional)

  - `axisTitleText` (bool; optional)

  - `colorbarPosition` (bool; optional)

  - `colorbarTitleText` (bool; optional)

  - `legendPosition` (bool; optional)

  - `legendText` (bool; optional): Edit the trace name fields from the legend.

  - `shapePosition` (bool; optional)

  - `titleText` (bool; optional): The global `layout.title`.

- `fillFrame` (bool; optional): If we DO autosize, do we fill the container or the screen?.

- `frameMargins` (number; optional): If we DO autosize, set the frame margins in percents of plot size.

- `linkText` (string; optional): Text appearing in the sendData link.

- `locale` (string; optional): The locale to use. Locales may be provided with the plot (`locales` below) or by loading them on the page, see: https://github.com/plotly/plotly.js/blob/master/dist/README.md#to-include-localization.

- `locales` (record; optional): Localization definitions, if you choose to provide them with the plot rather than registering them globally.

- `mapboxAccessToken` (bool | number | string | list | record; optional): Mapbox access token (required to plot mapbox trace types) If using an Mapbox Atlas server, set this option to '', so that plotly.js won't attempt to authenticate to the public Mapbox server.

- `modeBarButtons` (bool | number | string | list | record; optional): Fully custom mode bar buttons as nested array, where the outer arrays represents button groups, and the inner arrays have buttons config objects or names of default buttons.

- `modeBarButtonsToAdd` (list; optional): Add mode bar button using config objects.

- `modeBarButtonsToRemove` (list; optional): Remove mode bar button by name. All modebar button names at https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js Common names include: sendDataToCloud; (2D) zoom2d, pan2d, select2d, lasso2d, zoomIn2d, zoomOut2d, autoScale2d, resetScale2d; (Cartesian) hoverClosestCartesian, hoverCompareCartesian; (3D) zoom3d, pan3d, orbitRotation, tableRotation, handleDrag3d, resetCameraDefault3d, resetCameraLastSave3d, hoverClosest3d; (Geo) zoomInGeo, zoomOutGeo, resetGeo, hoverClosestGeo; hoverClosestGl2d, hoverClosestPie, toggleHover, resetViews.

- `plotGlPixelRatio` (number; optional): Increase the pixel ratio for Gl plot images.

- `plotlyServerURL` (string; optional): Base URL for a Plotly cloud instance, if `showSendToCloud` is enabled.

- `queueLength` (number; optional): Set the length of the undo/redo queue.

- `responsive` (bool; optional): Whether to change layout size when the window size changes.

- `scrollZoom` (bool; optional): Mousewheel or two-finger scroll zooms the plot.

- `sendData` (bool; optional): If we show a link, does it contain data or just link to a plotly file?.

- `showAxisDragHandles` (bool; optional): Enable axis pan/zoom drag handles.

- `showAxisRangeEntryBoxes` (bool; optional): Enable direct range entry at the pan/zoom drag points (drag handles must be enabled above).

- `showEditInChartStudio` (bool; optional): Should we show a modebar button to send this data to a Plotly Chart Studio plot. If both this and showSendToCloud are selected, only showEditInChartStudio will be honored. By default this is false.

- `showLink` (bool; optional): Link to open this plot in plotly.

- `showSendToCloud` (bool; optional): Should we include a modebar button to send this data to a Plotly Cloud instance, linked by `plotlyServerURL`. By default this is false.

- `showTips` (bool; optional): New users see some hints about interactivity.

- `staticPlot` (bool; optional): No interactivity, for export or image generation.

- `toImageButtonOptions` (record; optional): Modifications to how the toImage modebar button works.

  `toImageButtonOptions` is a record with keys:

  - `filename` (string; optional): The name given to the downloaded file.

  - `format` (a value equal to: 'jpeg', 'png', 'webp' or 'svg'; optional): The file format to create.

  - `height` (number; optional): Height of the downloaded file, in px.

  - `scale` (number; optional): Extra resolution to give the file after rendering it with the given width and height.

  - `width` (number; optional): Width of the downloaded file, in px.

- `topojsonURL` (string; optional): URL to topojson files used in geo charts.

- `watermark` (bool; optional): Add the plotly logo even with no modebar.

`loading_state` (record; optional): Object that holds the loading state object coming from dash-renderer.

`loading_state` is a record with keys:

- `component_name` (string; optional): Holds the name of the component that is loading.

- `is_loading` (bool; optional): Determines if the component is loading or not.

- `prop_name` (string; optional): Holds which property is loading.