用JavaScript实现直方图绘制,数据为2021的春节档电影票房统计(数据来源于豆瓣),代码如下:
<html>
<body>
<h2><center>2021春节档电影票房统计(单位:亿,截止到3.10日20:00)</center></h2>
<svg id="mysvg" width=800 height=600>
</svg>
<script>
//宽高适应网页
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
var svg=document.getElementById("mysvg");
svg.setAttribute("width",w);
svg.setAttribute("height",h);
var film=new Array("你好,李焕英","人潮汹涌","唐人街探案3","刺杀小说家","熊出没","哪吒重生","侍神令");
var box=new Array(51.60,6.20,44.42,9.82,5.74,4.29,2.70);
var rec=new Array(7);
var txt=new Array(7);
var title=new Array(7);
for(var i=0;i<7;i++){
rec[i]=document.createElement("rect");
svg.appendChild(rec[i]);
txt[i]=document.createElement("text");
svg.appendChild(txt[i]);
title[i]=document.createElement("titles");
svg.appendChild(title[i]);
rec[i].outerHTML="<rect x="+(i*w/rec.length)+" y="+(h-box[i]*10)+" width="+(0.8*w/rec.length)+" height="+(box[i]*10)+" fill='rgb(0,"+(50+box[i]*4)+",0)'>";
txt[i].outerHTML="<text x="+(i*w/rec.length)+" y="+(h-box[i]*10-10)+">"+box[i]+"</text>";
title[i].outerHTML="<text x="+(i*w/rec.length+40)+" y="+(h-box[i]*10-10)+">"+film[i]+"</text>";
}
</script>
</body>
</html>
下图为可视化结果: