如何控制 Chart.JS 饼图图例的位置及其外观?

How can I control the placement of my Chart.JS pie chart's legend, as well as its appearance?

我可以使用 Chart.JS 和以下代码创建饼图:

HTML

<div>
    <canvas id="top10ItemsChart" style="padding-left:20px" width="320" height="320"></canvas>
    <div id="top10Legend" class="chart-legend"></div>
</div>

jQuery

var data = [{
    value: 2755,
    color: "#FFE135",
    label: "Bananas"
}, {
    value: 2256,
    color: "#3B5323",
    label: "Lettuce, Romaine"
}, {
    value: 1637,
    color: "#fc6c85",
    label: "Melons, Watermelon"
}, {
    value: 1608,
    color: "#ffec89",
    label: "Pineapple"
}, {
    value: 1603,
    color: "#021c3d",
    label: "Berries"
}, {
    value: 1433,
    color: "#3B5323",
    label: "Lettuce, Spring Mix"
}, {
    value: 1207,
    color: "#046b00",
    label: "Broccoli"
}, {
    value: 1076,
    color: "#cef45a",
    label: "Melons, Honeydew"
}, {
    value: 1056,
    color: "#421C52",
    label: "Grapes"
}, {
    value: 1048,
    color: "#FEA620",
    label: "Melons, Cantaloupe"
}];

var optionsPie = { 
   legend: {
       display: true,
       position: 'right',
       labels: {
           fontColor: 'rgb(255, 99, 132)'
       }
  }
}

var ctx = $("#top10ItemsChart").get(0).getContext("2d");
var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
document.getElementById('top10Legend').innerHTML = top10PieChart.generateLegend();

问题是它将图例定位到饼图的底部,甚至在我希望饼图限制自身的 div 边界之外溢出和流血:

它还将图例呈现为简单的无序列表。我想做的是控制图例中各种元素的颜色("Banana" 应该与香蕉派(可以这么说)的颜色相同(#FFE135)等)

如何使 individual 元素匹配其各自数据点的颜色?

更新

官方文档中的"Legend Label Configuration"主题here表示可以设置图例的fontColor,但这是针对整个shebang的;我想知道的是,如何控制每个项目的颜色?

更新 2

为了至少让图例显示在所需位置,我将其添加到 jQuery:

var optionsPie = {
            legend: {
                display: true,
                position: 'right',
                labels: {
                    fontColor: 'rgb(255, 99, 132)'
                }
            }
        }

. . .
var myPieChart = new Chart(ctx).Pie(data, optionsPie);
document.getElementById("legendDiv").innerHTML = myPieChart.generateLegend();

...不过没什么区别-图例仍然挂在饼图的底部,它的字体仍然是默认的黑色。

更新 3

我使用了一些建议的代码,但图例仍然受重力影响而不是悬挂在右侧:

因此,图例影响了它下方的图表,而不是将其自身限制在自己的邻域内。

此外,我不希望要点充斥图例 - 彩色方块(和冗长的文字 - 还有数值)就是我所需要的。如何将图例从饼图的南边推到饼图的东边?

更新 4

我已经根据 this 重构了代码,它看起来更好了(我也向数据数组的 "label" 值添加了更多数据):

不过,如您所见,图例侵犯了其下方的象限。不过,饼图周围有一个 "ton" of empty/wasted space - 我想将饼图向左移动,图例向右移动。这也将允许更多的垂直 space 让馅饼成长。

我该怎么做?这是我现在使用的代码:

HTML

<div>
    <canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
    <div id="top10Legend"></div>
</div>

CSS

.pie-legend {
    list-style: none;
    margin: 0;
    padding: 0;
}

    .pie-legend span {
        display: inline-block;
        width: 14px;
        height: 14px;
        border-radius: 100%;
        margin-right: 16px;
        margin-bottom: -2px;
    }

    .pie-legend li {
        margin-bottom: 10px;
        display: inline-block;
        margin-right: 10px;
    }

JQUERY

    var data = [{
        value: 2755,
        color: "#FFE135",
        label: "Bananas: 2,755 (18%)"
    }, {
. . .            
}, {
        value: 1048,
        color: "#FEA620",
        label: "Melons, Cantaloupe: 1,048 (7%)"
    }];

    var optionsPie = {
        responsive: true,
        scaleBeginAtZero: true,
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
    }

    var ctx = $("#top10ItemsChart").get(0).getContext("2d");
    var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
    $("#top10Legend").html(top10PieChart.generateLegend());

注意:将此添加到 optionsPie:

legend: {
    display: true,
    position: 'right'
},

...什么都不做 - 这个传说仍然沉重地压在地板上,就像一只青蛙被鹌鹑弹填满了下巴。

更新 5

我试过 Teo 的例子,试图让它正常工作,但是,虽然它更好,但饼图很小,图例应该更宽,但我不知道如何水平拉伸图例,向各个方向拉伸饼图。现在是这样的:

这是现在的代码(JQUERY是一样的):

HTML

<div class="col-md-6">
    <div class="topleft">
        <h2 class="sectiontext">Top 10 Items</h2>
        <br />
        <div class="legendTable">
            <div class="legendCell">
                <canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
            </div>
            <div class="legendCell" id="top10Legend">
            </div>
        </div>
    </div>
</div>

CSS

    .topleft {
        margin-top: -4px;
        margin-left: 16px;
        margin-bottom: 16px;
        padding: 16px;
        border: 1px solid black;
    }

canvas {
    width: 100% !important;
    height: auto !important;
}

.legendTable {
    border: 1px solid forestgreen;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.legendCell {
    display: table-cell;
    vertical-align: middle;
}

.pie-legend ul {
    list-style: none;
    margin: 0;
    padding: 0;
    width: 300px;
}

.pie-legend span {
    display: inline-block;
    width: 14px;
    height: 12px;
    border-radius: 100%;
    margin-right: 4px;
    margin-bottom: -2px;
}

.pie-legend li {
    margin-bottom: 4px;
    display: inline-block;
    margin-right: 4px;
}

有些东西正在压扁馅饼并将图例的外边缘推到一起。

更新 6

Ochi 等人:这是我在代码 Ochification 后看到的:

这是我的代码 - 我什至按照你的方式订购了 jQuery,尽管我怀疑这是否真的有必要:

HTML

    <div class="row" id="top10Items">
        <div class="col-md-6">
            <div class="topleft">
                <h2 class="sectiontext">Top 10 Items</h2>
                <br />
                @*<div class="legendTable">
                    <div class="legendCell">
                        <canvas id="top10ItemsChart" class="pie" style="padding-left:20px"></canvas>
                    </div>
                    <div class="legendCell" id="top10Legend">
                    </div>
                </div>*@
                <div class="chart">
                    <canvas id="top10ItemsChart" class="pie"></canvas>
                    <div id="pie_legend"></div>
                </div>
            </div>
        </div>
    . . .
</div>

CSS

.pie-legend {
  list-style: none;
  margin: 0;
  padding: 0;
}

.pie-legend span {
  display: inline-block;
  width: 14px;
  height: 14px;
  border-radius: 100%;
  margin-right: 16px;
  margin-bottom: -2px;
}

.pie-legend li {
  margin-bottom: 10px;
  display: block;
  margin-right: 10px;
}

.chart,
#priceComplianceBarChart,
#pie_legend {
  display: inline-flex;
  padding: 0;
  margin: 0;
}

JQUERY

var optionsPie = {
    responsive: true,
    scaleBeginAtZero: true,
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
}

var ctx = $("#top10ItemsChart").get(0).getContext("2d");

var data = [{
    value: 2755,
    color: "#FFE135",
    label: "Bananas: 2,755 (18%)"
    . . .
}, {
    value: 1048,
    color: "#FEA620",
    label: "Melons, Cantaloupe: 1,048 (7%)"
}];

var top10PieChart = new Chart(ctx).Pie(data, optionsPie);
$("#pie_legend").html(top10PieChart.generateLegend());

...然而馅饼比大象身上的弹力裤更有弹性。

更新 7

可能存在配置问题或其他问题。我决定 "upgrade" 到 Chart.JS 的 2.1.3 版(从 1.0.2 版开始):

@*<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>*@
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.js"></script>

...并几乎完全复制了 Teo Dragovic 的 CodePen here

我唯一改变的是两个 CSS class 的名字("table" 变成了 "legendTable" 而 "cell" 变成了 "legendCell") table 边框的颜色从红色变为森林绿色,我现在明白了:

我是否还需要引用一个 Chart.JS CSS 文件或其他什么?

我想这是你想要的:DEMO

首先,您需要通过覆盖固定宽度和高度来使 canvas 具有响应能力,并将其包裹在可用于定位的附加 div 中。我使用 display: table 将元素居中,但如果您希望图表和图例采用与 50:50 不同的 space 数量,则将内部 div 设置为 inline-block 也可以。

HTML:

<div class="table">
    <div class="cell">
        <canvas id="top10ItemsChart" class="pie"></canvas>
    </div>
    <div class="cell" id="top10Legend"></div>
</div>

CSS:

canvas {
    width: 100% !important;
    height: auto !important;
}

.table {
    border: 1px solid red;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.cell {
    display: table-cell;
    vertical-align: middle;
}

更新: 根据 OP NEW DEMO

的附加信息做了一些调整

HTML:

<div class="container">
<div class="row">
<div class="col-md-6">
    <div class="topleft">
        <h2 class="sectiontext">Top 10 Items</h2>
        <br />
        <div class="chart">
            <div class="pie">
                <canvas id="top10ItemsChart" class="pie"></canvas>
            </div>
            <div class="legend" id="top10Legend">
            </div>
        </div>
    </div>
</div>
</div>
</div>

CSS:

    .topleft {
        margin-top: -4px;
        margin-left: 16px;
        margin-bottom: 16px;
        padding: 16px;
        border: 1px solid black;
    }

canvas {
    width: 100% !important;
    height: auto !important;
    margin-left: -25%;
}

.chart {
    border: 1px solid forestgreen;
    width: 100%;
    overflow: hidden;
    position: relative;
}

.pie {
    position: relative;
    padding: 10px 0;
    // adjust as necessary
    padding-left: 10px;
    padding-right: 0;
}

.legend {
    position: absolute;
    right: 10px;
    top: 10px;
    height: 100%;
    // adjust as necessary:
    width: 48%;
}

@media (max-width: 480px) {
    .legend {
        position: relative;
        width: 100%;
    }
    .pie {
        margin: 0;
    }
}

.pie-legend ul {
    list-style: none;
    margin: 0;
    padding: 0;
    width: 300px;
}

.pie-legend span {
    display: inline-block;
    width: 14px;
    height: 12px;
    border-radius: 100%;
    margin-right: 4px;
    margin-bottom: -2px;
}

.pie-legend li {
    margin-bottom: 4px;
    display: inline-block;
    margin-right: 4px;
}

使用 Chart.JS 的第 2 版时(或多或少)这是可行的:

HTML

<h2 class="sectiontext">Top 10 Items</h2>
<br />
<div class="chart">
    <canvas id="top10ItemsChart" class="pie"></canvas>
    <div id="pie_legend"></div>
</div>

JQUERY

var data = {
    labels: [
        "Bananas: 2,755 (18%)",
        "Lettuce, Romaine: 2,256 (14%)",
        "Melons, Watermelon: 1,637 (10%)",
        "Pineapple: 1,608 (10%)",
        "Berries: 1,603 (10%)",
        "Lettuce, Spring Mix: 1,433 (9%)",
        "Broccoli: 1,207 (8%)",
        "Melons, Honeydew: 1,076 (7%)",
        "Grapes: 1,056 (7%)",
        "Melons, Cantaloupe: 1,048 (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
}

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

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

我说,"more or less"因为馅饼还是小得可怜:

如@B.ClayShannon所述,版本 2 与版本 1 有很大不同。以下是如何使用版本 2 自定义图例模板的示例。

options: {
    legendCallback: function (chart) {
        var text = [];
        text.push('<ul class="' + chart.id + '-legend" style="list-style:none">');
        for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
            text.push('<li><div style="width:10px;height:10px;display:inline-block;background:' + chart.data.datasets[0].backgroundColor[i] + '" />&nbsp;');
            if (chart.data.labels[i]) {
                text.push(chart.data.labels[i]);
            }
            text.push('</li>');
        }
        text.push('</ul>');

        return text.join('');
    },
    legend: {display: false},
}

它没有直接显示在上面接受的解决方案中,但要在其他地方呈现您的图例,您需要调用:

$("#myChartLegend").html(myChart.generateLegend()); 

最后,一些 HTML 将其组合在一起(注意 clearfix 是一个 Bootstrap class :

<div class="chart">
    <div style="float:left">
        <canvas id="myChart" class="pie" style="max-width:300px;"></canvas>
    </div>

    <div class="legend" id="myChartLegend" style="float:left;"></div>
    <div style="clear: both;"/>
</div>