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

时间:2018-11-15 20:45:03

标签: 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);
    <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>

1 个答案:

答案 0 :(得分:1)

您可以通过设置xy的值来放置legend。对于您的图形,它类似于:

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;">