代码之家  ›  专栏  ›  技术社区  ›  Maihan Nijat

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

  •  2
  • Maihan Nijat  · 技术社区  · 6 年前

    我想在图表顶部,但在标题下显示图例。我找了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 回复  |  直到 6 年前
        1
  •  1
  •   Maximilian Peters    6 年前

    您可以定位 legend 通过设置 x y 价值观。对于您的图表,它将类似于:

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