Javascript 使用 Chartist.js 如何更改圆环图的笔触颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35402143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Chartist.js how do you change the color of the stroke for a donut chart?
提问by Crystal O'Mara
Hello I am trying to create the following donut chart using Chartist.js:
您好,我正在尝试使用 Chartist.js 创建以下圆环图:
This is what the chart looks like currently:
这是图表目前的样子:
I am trying to find where or how I can change the colors of this chart to match the 1st donut chart. The red and pink seem to be the defaults. I haven't been able to find any documentation of how to accomplish this goal. I would also like to customize the size of the stroke and the size of the chart itself. Any help is greatly appreciated!
我试图找到在哪里或如何更改此图表的颜色以匹配第一个圆环图。红色和粉红色似乎是默认设置。我一直无法找到有关如何实现此目标的任何文档。我还想自定义笔画的大小和图表本身的大小。任何帮助是极大的赞赏!
Current code:
当前代码:
// ** START CHARTIST DONUT CHART ** //
var chart = new Chartist.Pie('.ct-chart', {
series: [70, 30],
labels: [1, 2]
}, {
donut: true,
showLabel: false
});
chart.on('draw', function(data) {
if(data.type === 'slice') {
// Get the total path length in order to use for dash array animation
var pathLength = data.element._node.getTotalLength();
// Set a dasharray that matches the path length as prerequisite to animate dashoffset
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
// Create animation definition while also assigning an ID to the animation for later sync usage
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 1000,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeOutQuint,
// We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
fill: 'freeze'
}
};
// If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
if(data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
// We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
// We can't use guided mode as the animations need to rely on setting begin manually
// See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
data.element.animate(animationDefinition, false);
}
});
// ** END CHARTIST DONUT CHART ** //
HTML:
HTML:
<div class="ct-chart ct-perfect-fourth"></div>
回答by Crystal O'Mara
So I figured it out...
所以我想通了...
I had to go into css and override the defaults. I had to make sure that the css file was loaded after the cdn for Chartist. Then just set width and height of ct-chart.
我不得不进入 css 并覆盖默认值。我必须确保在 Chartist 的 CDN 之后加载了 css 文件。然后只需设置 ct-chart 的宽度和高度。
.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut {
stroke: #0CC162;
}
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: #BBBBBB;
}
.ct-chart {
margin: auto;
width: 300px;
height: 300px;
}
Then I had to add donutWidth key to the chart object to set the stroke width:
然后我不得不将 donutWidth 键添加到图表对象以设置笔触宽度:
var chart = new Chartist.Pie('.ct-chart', {
series: [7, 3],
labels: [1, 2]
}, {
donut: true,
donutWidth: 42,
showLabel: false
});
回答by Ageonix
Chartist relies on modifying CSS to control the colors, sizes, etc. of the charts. I'd suggest having a look at the documentation here to learn lots of cool tips and tricks: https://gionkunz.github.io/chartist-js/getting-started.html
Chartist 依靠修改 CSS 来控制图表的颜色、大小等。我建议查看此处的文档以了解许多很酷的技巧和窍门:https: //gionkunz.github.io/chartist-js/getting-started.html
But to your specific question, here's an except from the above link that tells you how to control the donut chart:
但是对于您的具体问题,上面链接中的一个除外,它告诉您如何控制圆环图:
/* Donut charts get built from Pie charts but with a fundamentally difference in the drawing approach. The donut is drawn using arc strokes for maximum freedom in styling */
.ct-series-a .ct-slice-donut {
/* give the donut slice a custom colour */
stroke: blue;
/* customize stroke width of the donut slices in CSS. Note that this property is already set in JavaScript and label positioning also relies on this. In the right situation though it can be very useful to style this property. You need to use !important to override the style attribute */
stroke-width: 5px !important;
/* create modern looking rounded donut charts */
stroke-linecap: round;
}
回答by Jeremy Thomas
A little later here, but you can provide class names to the data series to allow you to change the colors on each graph independently:
稍后在这里,但您可以为数据系列提供类名称,以允许您独立更改每个图形上的颜色:
From the docs:
从文档:
The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
series 属性也可以是包含 value 属性和 className 属性的值对象数组,以覆盖系列组的 CSS 类名称。
Instead of:
代替:
series: [70, 30]
Do this:
做这个:
series: [{value: 70, className: 'foo'}, {value: 30, className: 'bar'}]
and then you can style however you'd like with the stroke
css property
然后您可以使用stroke
css 属性设置任何您喜欢的样式
回答by Felix II Rigor
I've managed to change the stroke color by overriding this class. You can change ct-series-b to which bar graph you change to change color (ct-series-a, ct-series-b and etc).
我已经通过覆盖这个类设法改变了笔触颜色。您可以将 ct-series-b 更改为要更改颜色的条形图(ct-series-a、ct-series-b 等)。
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.css" />
<style>
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: goldenrod;
}
</style>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.js"></script>
<script>
window.onload = function() {
var data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
series: [
[5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
[3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
]
};
var options = {
seriesBarDistance: 10
};
var responsiveOptions = [
['screen and (max-width: 640px)', {
seriesBarDistance: 5,
axisX: {
labelInterpolationFnc: function (value) {
return value[0];
}
}
}]
];
new Chartist.Bar('.ct-chart', data, options, responsiveOptions);
}
</script>
</body>
</html>
回答by Mark Miller
The answers above wont work for me since I'm dynamically excluding categories with 0 points. You can do it pragmatically though. You can directly modify the svg node. My charts use fill instead of stroke but the method should be the same. This worked for me in Chrome:
上面的答案对我不起作用,因为我动态排除了 0 分的类别。不过,您可以务实地做到这一点。可以直接修改svg节点。我的图表使用填充而不是描边,但方法应该是相同的。这在 Chrome 中对我有用:
const data = {
series: [],
labels: []
};
const pieColors = [];
enrollment.CoverageLevelTotals.forEach(e => {
if (e.Total === 0) return;
data.series.push(e.Total);
data.labels.push(e.Total);
pieColors.push(colors[e.CoverageLevel]);
});
new Chartist.Pie(document.getElementById(canvasId), data,
{
width: '160px',
height: '160px',
donut: true,
donutWidth: 50,
donutSolid: true,
showLabel: (data.series.length > 1)
}).on('draw',function (data) {
if (data.type !== 'slice') return;
data.element._node.setAttribute('style','fill:' + pieColors[data.index]);
});
}
}
回答by Somerussian
This code worked for me to change the color of the stroke:
这段代码对我有用,可以改变笔画的颜色:
// Prepare chart params
var chartColors = ['orange'];
var chartWidth = 9;
var percent = 77;
var arc = percent ? 360 * percent / 100 : 0;
// Create chart
var chart = new Chartist.Pie('.my-donut', {
series: [arc],
labels: [percent + '%'],
}, {
donut: true,
donutWidth: chartWidth,
startAngle: 0,
total: 360,
});
// Set chart color
chart.on('draw', function(data) {
if(data.type === 'slice') {
if (chartColors[data.index]) {
data.element._node.setAttribute('style','stroke: ' + chartColors[data.index] + '; stroke-width: ' + chartWidth + 'px');
}
}
});
回答by lubosdz
Bar charts with a single serie - use nth-child(N)
:
具有单个系列的条形图 - 使用nth-child(N)
:
.ct-bar:nth-child(1){
stroke: #379683 !important;
}
.ct-bar:nth-child(2){
stroke: #91A453 !important;
}
.ct-bar:nth-child(3){
stroke: #EFB200 !important;
}