问题
I'm creating a fairly simple pie chart with Chart.JS like so:
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());
It looks decent:
...but I want the pie on the left and the legend on the right, with the legend vertically stacked. How can I accompilish that objective?
UPDATE
I tried this:
CSS
.pieLegend li span {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 5px;
}
HTML
<div id="pie_legend" class="pieLegend"></div>
...as suggested in the accepted answer here, but it makes no difference whatsoever.
UPDATE 2
Fixing the bad ID caused the new legend to display, and adding the "display: false" to the options caused the original one to disappear, but the new one still appears below the pie, crowding outside of its div and bleeding into the quadrant below it (shown hovering over bananas):
UPDATE 3
Here's how it looks with the accepted answer's code applied:
The pie is still puny, but this is much better than it was (and answers the question).
回答1:
You have to turn the default legend off in the options first with:
legend: {
display: false
},
Also your id
selector for your legend was wrong. Fiddle.
Wrap the chart in the <div>
and set the height and width of that since the canvas will be responsive to its container, then set the canvas's div
and the legend's div
as display: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;
}
回答2:
Another way to right align the legend is to add:
legend: {
position:"right"
}
To the Chart options
JSfiddle
来源:https://stackoverflow.com/questions/39645440/how-can-i-cause-a-legend-to-appear-to-the-right-of-the-pie-chart-js