如何在 Plotly 中将图例放置在顶部而不是底部?

Mai*_*jat 11 javascript plotly

我想在图表顶部、标题下方显示图例。我查找了API,没有找到任何与改变位置相关的内容,只是设置方向。

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);
Run Code Online (Sandbox Code Playgroud)
    <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>
Run Code Online (Sandbox Code Playgroud)

Max*_*ers 10

legend您可以通过设置其x和值来定位y。对于你的图表来说,它会是这样的:

legend: {x: 0.4, y: 1.2}
Run Code Online (Sandbox Code Playgroud)

legend: {x: 0.4, y: 1.2}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)


I_m*_*que 10

添加:

layout(legend = list(orientation = 'h', xanchor = "center", x = 0.5, y= 1)) 
Run Code Online (Sandbox Code Playgroud)

使图例处于水平、中间和顶部。