Maihan Nijat
Maihan Nijat

Reputation: 9344

How to position legend on top instead of bottom in Plotly?

I want to display the legend on the top of chart, but under the title. I looked for the API, and did not find anything related changing position, but only setting orientation.

var myData = [
    {
        fcst_valid_local: "2013-01-04 22:23:00",
        pop: 20,
        temp: 38,
    },
    {
        fcst_valid_local: "2013-02-04 22:23:00",
        pop: 15,
        temp: 39,
    },
    {
        fcst_valid_local: "2013-03-04 22:23:00",
        pop: 2,
        rh: 70,
    }

];

var data = [
    {
        x: myData.map(d => d.fcst_valid_local),
        y: myData.map(d => d.temp),
        type: 'line'
    },
    {
        x: myData.map(d => d.fcst_valid_local),
        y: myData.map(d => d.pop),
        type: 'bar',
        yaxis: 'y2'
    }
];

var layout = {
    title: 'Daily Forecast',
    yaxis: {
        autorange: true,
        range: [0, 100],
    },
    yaxis2: {
        range: [0, 100],
        side: 'right',
        overlaying: 'y',
        type: 'linear'
    },
    legend: {orientation: 'h', side: 'top'}
};

Plotly.newPlot('myDiv', data, layout);
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>

Upvotes: 12

Views: 25168

Answers (2)

LeMarque
LeMarque

Reputation: 783

add:

layout(legend = list(orientation = 'h', xanchor = "center", x = 0.5, y= 1)) 

to fit legend as horizontal, in the middle and at the top.

Upvotes: 10

Maximilian Peters
Maximilian Peters

Reputation: 31679

You can position the legend by setting its x and y values. For your graph it would be something like:

legend: {x: 0.4, y: 1.2}

var myData = [
    {
        fcst_valid_local: "2013-01-04 22:23:00",
        pop: 20,
        temp: 38,
    },
    {
        fcst_valid_local: "2013-02-04 22:23:00",
        pop: 15,
        temp: 39,
    },
    {
        fcst_valid_local: "2013-03-04 22:23:00",
        pop: 2,
        rh: 70,
    }

];

var data = [
    {
        x: myData.map(d => d.fcst_valid_local),
        y: myData.map(d => d.temp),
        type: 'line'
    },
    {
        x: myData.map(d => d.fcst_valid_local),
        y: myData.map(d => d.pop),
        type: 'bar',
        yaxis: 'y2'
    }
];

var layout = {
    title: 'Daily Forecast',
    yaxis: {
        autorange: true,
        range: [0, 100],
    },
    yaxis2: {
        range: [0, 100],
        side: 'right',
        overlaying: 'y',
        type: 'linear'
    },
    legend: {x: 0.4, y: 1.2}
};

Plotly.newPlot('myDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width: 480px; height: 400px;">

Upvotes: 11

Related Questions