0

我正在使用 Chart.JS 创建一个相当简单的饼图,如下所示:

var data = {
    labels: [
        "Bananas (18%)",
        "Lettuce, Romaine (14%)",
        "Melons, Watermelon (10%)",
        "Pineapple (10%)",
        "Berries (10%)",
        "Lettuce, Spring Mix (9%)",
        "Broccoli (8%)",
        "Melons, Honeydew (7%)",
        "Grapes (7%)",
        "Melons, Cantaloupe (7%)"
    ],
    datasets: [
        {
            data: [2755, 2256, 1637, 1608, 1603, 1433, 1207, 1076, 1056, 1048],
            backgroundColor: [
                "#FFE135",
                "#3B5323",
                "#fc6c85",
                "#ffec89",
                "#021c3d",
                "#3B5323",
                "#046b00",
                "#cef45a",
                "#421C52",
                "#FEA620"
            ]
        }
    ]
};

var optionsPie = {
    responsive: true,
    scaleBeginAtZero: true,
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                return data.labels[tooltipItem.index] + ": " +
                    formatter.format(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]);
            }
        }
    }
};

var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx,
{
    type: 'pie',
    data: data,
    options: optionsPie
});

$("#top10Legend").html(top10PieChart.generateLegend());

它看起来不错:

在此处输入图像描述

...但我想要左边的饼图和右边的图例,图例垂直堆叠。我怎样才能实现这个目标?

更新

我试过这个:

CSS

.pieLegend li span {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-right: 5px;
}

HTML

<div id="pie_legend" class="pieLegend"></div>

...正如在此处接受的答案中所建议的那样,但这没有任何区别。

更新 2

修复错误 ID 会导致新图例显示,并在选项中添加“display: false”会导致原来的图例消失,但新图例仍然出现在饼图下方,拥挤在其 div 之外并渗入下方的象限它(显示为悬停在香蕉上):

在此处输入图像描述

更新 3

以下是应用接受的答案代码后的外观:

在此处输入图像描述

馅饼仍然微不足道,但这比以前好多了(并回答了问题)。

4

2 回答 2

1

您必须首先在选项中关闭默认图例:

legend: {
        display: false
},

id的图例选择器也是错误的。 小提琴

将图表包裹在 中<div>并设置其高度和宽度,因为画布将响应其容器,然后将画布div和图例设置divdisplay:inline-block

HTML

<div id="kpi">
    <div id="container">
      <canvas id="top10ItemsChart"></canvas>
    </div>
    <div id="top10Legend" class="pieLegend"></div>
</div>

CSS

 #kpi{
      height: 400px;
      width: 100%;
      border: 1px solid black;
      background-color: white;
    }
    .pieLegend li span {
      display: inline-block;
      width: 12px;
      height: 12px;
      margin-right: 5px;
    }

    #top10Legend {
      display: inline-block;
    }

    #container {
      display: inline-block;
      height: 50%;
      width: 50%;
    }

    #top10Legend>ul{
      list-style:none;
    }
于 2016-09-22T18:29:43.180 回答
1

右对齐图例的另一种方法是添加:

legend: {
   position:"right"
}

到图表选项

JSfiddle

于 2016-11-21T12:47:07.560 回答