gpt4 book ai didi

javascript - 如何在 morris.js 条形图上放置文本

转载 作者:可可西里 更新时间:2023-11-01 02:37:48 25 4
gpt4 key购买 nike

我有一个 morris.js 条形图。我想将 count 放在这张图的顶部。我调查了morris.js bar doc , 找不到任何。

悬停时它应该显示 value 但在栏的顶部它应该显示 count。有没有办法做到这一点?类似于给定图像的东西

enter image description here

这是我的代码

Morris.Bar ({
element: 'bar-example',
data: [
{mapname: 's1', value: 10, count: 3},
{mapname: 's2', value: 4, count: 4},
{mapname: 's3', value: 12, count: 13}
],
xkey: 'mapname',
ykeys: ['value'],
labels: ['No. of days'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: function (row, series, type) {
console.log("--> "+row.label, series, type);
if(row.label == "s1") return "#AD1D28";
else if(row.label == "s2") return "#DEBB27";
else if(row.label == "s3") return "#fec04c";
}
});

Here is a link您可以在哪里进行测试。

最佳答案

我刚刚在寻找相同的解决方案时发现了这个问题。这是在 javascript/jquery 中完成的。

我可以与您分享我正在使用的代码,这些代码是我通过反复试验、错误和研究发现的。

function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}

var theData = [
{mapname: 's1', value: 10, count: 3},
{mapname: 's2', value: 4, count: 4},
{mapname: 's3', value: 12, count: 13}
]

Morris.Bar ({
element: 'bar-example',
data: theData,
xkey: 'mapname',
ykeys: ['value'],
labels: ['No. of days'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: function (row, series, type) {
console.log("--> "+row.label, series, type);
if(row.label == "s1") return "#AD1D28";
else if(row.label == "s2") return "#DEBB27";
else if(row.label == "s3") return "#fec04c";
}
});

var items = $("#bar-example").find( "svg" ).find("rect");
$.each(items,function(index,v){
var value = theData[index].count;
var newY = parseFloat( $(this).attr('y') - 20 );
var halfWidth = parseFloat( $(this).attr('width') / 2 );
var newX = parseFloat( $(this).attr('x') ) + halfWidth;
var output = '<text style="text-anchor: middle; font: 12px sans-serif;" x="'+newX+'" y="'+newY+'" text-anchor="middle" font="10px &quot;Arial&quot;" stroke="none" fill="#000000" font-size="12px" font-family="sans-serif" font-weight="normal" transform="matrix(1,0,0,1,0,6.875)"><tspan dy="3.75">'+value+'</tspan></text>';
$("#bar-example").find( "svg" ).append(parseSVG(output));
});

输出看起来像这样。

enter image description here

但是您可以尝试更改此处的值

var newY = parseFloat( $(this).attr('y') - 20 );

类似于

var halfHeight = parseFloat( $(this).attr('height') / 2 );
var newY = parseFloat( $(this).attr('y') - halfHeight );

此更改未经测试,但可以作为一个很好的起点。

问候 :)

关于javascript - 如何在 morris.js 条形图上放置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23537788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com