我正在尝试使用 C3 和 D3 创建条形图,但我无法让列彼此无关,除了它们在 Y 轴上使用相同的刻度这一事实。
为了更好地解释,我添加了图片。
var chart = c3.generate({
bindto: '#designerChart',
data: {
columns: [
['MA', 6],
['ME', 8],
['NY', 6],
['CN', 5],
['TX', 2]
],
type: 'bar',
},
axis: {
y: {
max: 10,
min: 0,
padding: { top: 0, bottom: 0 }
}
}
});
结果是一组条形图,当我将鼠标悬停在它们上方时,我得到了所有条形图的详细信息 - 这不是我想要的。
我可以更改数据,以便它显示单独的列,但它们的颜色相同,当我想将其转换为饼图时,您无法区分状态。
var chart = c3.generate({
bindto: '#designerChart',
data: {
x: 'x',
columns: [
['x','MA', 'ME', 'NY', 'CN', 'TX'],
['rainfall', 6, 8, 6, 5, 4 ]
],
type: 'bar',
},
axis: {
x: {
type: 'category'
},
y: {
max: 10,
min: 0,
padding: { top: 0, bottom: 0 }
}
}
});
这就是我想要的:
最佳答案
条形图解决方案:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>C3 Bar Chart</title>
</head>
<body>
<div id="designerChart"></div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
columnColors = ['#9a4d6f', '#c76c47', '#f85115', '#d9b099', '#d4ba2f'];
function setColumnBarColors(colors, chartContainer) {
$('#' + chartContainer + ' .c3-chart-bars .c3-shape').each(function(index) {
this.style.cssText += 'fill: ' + colors[index] + ' !important; stroke: ' + colors[index] + '; !important';
});
$('#' + chartContainer + ' .c3-chart-texts .c3-text').each(function(index) {
this.style.cssText += 'fill: ' + colors[index] + ' !important;';
});
}
var chart = c3.generate({
bindto: '#designerChart',
data: {
columns: [
['rainfall', 6, 8, 6, 5, 4]
],
type: 'bar'
},
axis: {
x: {
label: {
text: 'States',
position: 'outer-center',
},
type: 'category',
categories: ['MA', 'ME', 'NY', 'CN', 'TX'],
tick: {
centered: true
}
},
y: {
label: {
text: 'Rainfall (inches)',
position: 'outer-middle'
},
max: 10,
min: 0,
padding: {
top: 0,
bottom: 0
}
}
},
legend: {
show: false
}
});
setColumnBarColors(columnColors, 'designerChart');
// Color turns to original when window is resized
// To handle that
$(window).resize(function() {
setColumnBarColors(columnColors, 'designerChart');
});
});
</script>
</body>
</html>
在此 fiddle (整页)中,颜色变为原始颜色。但它会根据工作本地文件以及 c3、d3 和 jquery 的本地引用改变颜色。
引用资料:
- setColumnBarColors 函数:
jzcor...@gmail.com https://groups.google.com/forum/ - http://c3js.org/gettingstarted.html
- http://c3js.org/samples/axes_x_tick_format.html
- http://c3js.org/reference.html
关于javascript - 使用 C3 在 x 轴上使用单独的列制作简单的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33315769/