简体   繁体   English

使用字典在 D3.js 中绘制图形

[英]Using a dictionary to plot graph in D3.js

I have a dictionary of the form:我有一个形式的字典:

[('2019-10', 273), ('2019-11', 299), ('2019-12', 244), ('2020-01', 231), ('2020-02', 232)]

I want to plot this dictionary as a graph, with the dates as the x axis and the corresponding values as the bars.我想将此字典绘制为图形,以日期为 x 轴,将相应的值作为条形。 How can I achieve this?我怎样才能做到这一点? I am new to D3, hence have very little knowledge of it.我是 D3 的新手,因此对它知之甚少。 Any help is appreciated!任何帮助表示赞赏!

Assuming that your data is in the format:假设您的数据采用以下格式:

[{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}]

You could first apply some mapping function to transform this into a more convenient format and go from there, eg:您可以先应用一些映射函数将其转换为更方便的格式,然后从那里开始,例如:

 var height = 200; var width = 400; var data = [{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}]; var mapped = data.map(d => { return { date: Object.keys(d)[0], count: d[Object.keys(d)[0]] } }); var x = d3.scale.ordinal().rangeRoundBands([0, width], .05); var y = d3.scale.linear().range([height, 0]); x.domain(mapped.map(d => d.date)); y.domain([0, d3.max(mapped, d => d.count)]); var svg = d3.select("#simple").append("svg") .attr("width", width) .attr("height", height); svg.selectAll("bar") .data(mapped) .enter().append("rect") .style("fill", "steelblue") .attr("x", d => x(d.date)) .attr("width", x.rangeBand()) .attr("y", d => y(d.count)) .attr("height", d => height - y(d.count));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script> <div id="simple"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM