Search code examples
f#plotly

Moving the legend in plotly f#


I've been trying to move the legend in a plotly plot to the top or the bottom of the plot to maintain uniform sizes of plots with different legnds but I have been unable to do so. Even the plotly documentation has not been very helpful. Does anyone know how to do this?

I tried moving the legend for this example code but I have not been successfull.


let chart = Chart.Scatter(xs,
             [10.; 20.; nan; 15.; 10.; 5.; 15.;nan; 20.; 10.; 10.; 15.; 25.; 20.; 10.], 
             StyleParam.Mode.Lines_Markers, Name="<b>No</b> Gaps")             
             |> GenericChart.mapTrace (Trace2DStyle.Scatter(ConnectGaps = true))
[
    
    chart;
    Chart.Scatter(xs,
             [5.; 15.; nan; 10.; 5.; 0.; 10.; nan; 15.; 5.; 5.; 10.; 20.; 15.; 5.], 
             StyleParam.Mode.Lines_Markers, Name="Gaps")
] |> Chart.combine

Thanks!


Solution

  • This GitHub comment gives some relevant info for Plotly.NET 2.0. In short, you can move the legend to the top of the plot like this:

    open Plotly.NET.LayoutObjects
    
    let myLegend = 
        Legend.init(
            Orientation = StyleParam.Orientation.Horizontal,
            Y = 1.1
        )
    
        ...
        |> Chart.combine
        |> Chart.withLegend(myLegend)
    

    enter image description here

    Setting Y to 0.0 instead will put the legend below the chart.

    enter image description here

    More details on Legend.init can be found here.