d3.js 数据可视化负数
Making Data-Visualizations using D3.js
使用D3.js进行数据可视化
What is it?
它是什么?
According to d3js.org (where you will download d3.js) D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.
根据d3js.org(您将在其中下载d3.js)的介绍,D3.js是一个JavaScript库,用于基于数据处理文档。 D3可帮助您使用HTML,SVG和CSS使数据栩栩如生。 D3对Web标准的重视为您提供了现代浏览器的全部功能,而又不会使自己陷入专有框架,而是结合了强大的可视化组件和数据驱动的DOM操作方法。
What it is not.
不是什么
Before we get started looking at a visualization, we should clarify what d3.js is not. It is not a replacement or competitor to angular, backbone or any other web UI framework, nor is it meant to replace jQuery, a popular (Document Object Model) selection/manipulation framework. It is true that you can do data visualizations using jQuery, plain old javascript or many of the UI frameworks but d3.js’s power is really its ability to bind arbitrary data to the (DOM).
在开始查看可视化之前,我们应该弄清楚d3.js不是什么。 它不是角度,主干或任何其他Web UI框架的替代品或竞争对手,也不意味着替代流行的(文档对象模型)选择/操作框架jQuery。 确实可以使用jQuery,普通的旧javascript或许多UI框架进行数据可视化,但是d3.js的强大功能实际上是将任意数据绑定到(DOM)的能力。
Examples
例子
There are numerous examples of data visualizations using d3.js. Unfortunately, almost all examples use a .TSR datasource, which would be a flat file that sits on your server. If you are here wanting to learn about d3.js you are likely interested in its dynamic properties. You don’t want to write your data into a flat file and stick it out on the web. You're hopefully more interested in implementing dynamic real time data visualizations, and consequently in this tutorial we will be working with JSON for our data source unlike most of the tutorials out there. This will better allow you to get started quickly in creating real-time data visualizations for the web. You can look at other examples below after you have followed through on this tutorial.
有许多使用d3.js进行数据可视化的示例。 不幸的是,几乎所有示例都使用.TSR数据源,它是位于服务器上的平面文件。 如果您想了解d3.js,则可能会对它的动态属性感兴趣。 您不想将数据写入平面文件并将其粘贴到网络上。 希望您对实现动态实时数据可视化更感兴趣,因此,在本教程中,我们将为数据源使用JSON,这与大多数教程不同。 这将更好地帮助您快速开始为Web创建实时数据可视化。 在完成本教程的学习之后,您可以查看下面的其他示例。
Sample d3.js visualizations (http://christopheviau.com/
样本d3.js可视化( http://christopheviau.com/ d3list / gal lery.html )
Lets get started
让我们开始吧
D3.js has really opened up the possibilities for data visualizations. The sky is really the limit and there are some amazingly creative charts or visualizations that you can make. That being said, the bar graph is STILL a time tested and effective mechanism to display the message of data effectively. I wanted to give you something that you could implement today in projects you might be working on and the visualization that is likely still most applicable is going to be the bar graph. There are many other examples you can look at once you get the basics down. So lets get started.
D3.js确实为数据可视化打开了可能性。 天空确实是极限,您可以制作一些惊人的创意图表或可视化效果。 就是说,条形图仍然是经过时间测试的有效机制,可以有效地显示数据消息。 我想为您提供一些您今天可以在您正在从事的项目中实施的东西,而可能仍然最适用的可视化将是条形图。 掌握基础知识后,您还可以查看许多其他示例。 因此,让我们开始吧。
You can download d3.js at http://d3js.org/ or you can use a hosted absolute reference like I will be doing as below.
您可以从http://d3js.org/下载d3.js,也可以使用托管的绝对引用,如下所示。
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
If you have spent time as a front end developer, you know how tedious it can be to modify the W3C specified DOM. JQuery’s popularity in recent years is many explained by its approach to simplify this methodology. jQuery typical calls these “Selectors”. In d3.js, they work similarly but are called … well “Selections”. Working with “Selections” in mass gives d3.js a lot of its power.
如果您花了很多时间作为前端开发人员,那么您就会知道修改W3C指定的DOM是多么繁琐的工作。 近年来,JQuery简化了该方法的方法可以解释很多。 jQuery通常将这些称为“选择器”。 在d3.js中,它们的工作方式类似,但被称为“精选”。 大量使用“选择”可以使d3.js发挥更大的作用。
Selections
选择项
selectAll() and select() are some of the main selections used. For example selectAll()和select()是一些使用的主要选择。 例如d3.selectAll(“p”).style(“font-size”, 12);
You could just as easily select an individual element as well
您也可以轻松选择单个元素
d3.select(“body”).style(“font-size”, 12);
Chaining methods
链接方式
Like jquery you can chain methods saving time in d3.js.
像jquery一样,您可以在d3.js中链接方法以节省时间。
d3.select(“body”)
.style(“font-size”, 12)
.style(“color”, “#333333”);
Lets do a full example.
让我们举一个完整的例子 。
We will use a popular example by Mike Bostock as a starting point, however as mentioned before we will be using JSON data instead. We will adjust other elements as well. I will also be including some references to the API to allow you to dig a little deeper on each line of code if you have questions.
我们将以Mike Bostock的流行示例作为起点,但是如前所述,我们将改用JSON数据。 我们还将调整其他元素。 我还将包括对API的一些引用,如果您有疑问,可以使您对每行代码进行更深入的了解。
THE CSS
CSS
I'll start with the CSS, I won’t spend much time here as you will likely see how this affects the project as it comes together, but here is the CSS we will be using
我将从CSS开始,在这里我不会花很多时间,因为您可能会看到它如何影响项目,因为它会在一起,但是这里是我们将使用CSS
<style>
#chart rect{
fill: #4aaeea;
}
#chart text{
fill: black;
font: 10px sans-serif;
text-anchor: end;
}
.axis text{
font: 10px sans-serif;
}
.axis path, .axis line{
fill: none;
stroke : #333;
shape-rendering: crispEdges;
}
body{
color : #333333;
padding-top : 50px;
} </style>
The one element you are probably not familiar with is shape-rendering: crispEdges
您可能不熟悉的一个元素是形状渲染:crispEdges
This is part of CSS that can help us define our SVG elements. Remember SVG are Vector Graphics instead of Pixel based graphics and consequently some of the new CSS specifications help us to deal with them. We are going to want crispEdges so we will include the new shape-rendering: crispEdges to accomplish this.
这是CSS的一部分,可以帮助我们定义SVG元素。 请记住,SVG是矢量图形,而不是基于像素的图形,因此,一些新CSS规范可帮助我们处理这些图形。 我们将需要crispEdges,因此我们将包括新的形状渲染:crispEdges以实现此目的。
Other than that most of the CSS should be a pretty self-explanatory. If you still have additional questions just google the attributes you don't understand and you should be able to answer everything. After all this is about d3.js not CSS :).
除此之外,大多数CSS应该是不言自明的。 如果您还有其他问题,只需在Google上搜索您不了解的属性,就可以回答所有问题。 毕竟,这是关于d3.js而不是CSS的:)。
THE JAVASCRIPT
JAVASCRIPT
I'll post it all initially then spend some time going over each section...
我先将其发布,然后再花一些时间浏览每个部分...
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var margin ={top:40, right:40, bottom:40, left:40},
width=900-margin.left - margin.right,
height=500-margin.top-margin.bottom;
var x = d3.scale.ordinal().rangeRoundBands([0, width], .5);
var y = d3.scale.linear().range([height, 0]);
var chart = d3.select("#chart")
.append("svg") //append svg element inside #chart
.attr("width", width+(2*margin.left)+margin.right) //set width
.attr("height", height+margin.top+margin.bottom); //set height
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
d3.json("data.json", function(error, data){
var pxAboveBar = 10;
var ymax = d3.max(d3.values(data));
x.domain(data.map(function(d){ return d.country}));
y.domain([0, ymax.gdp + 2]);
var bar = chart.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i){
return "translate("+x(d.country)+", 0)";
});
bar.append("rect")
.attr("y", function(d) {
return y(d.gdp);
})
.attr("x", function(d,i){
return x.rangeBand();
})
.attr("height", function(d) {
return height - y(d.gdp);
})
.attr("width", x.rangeBand());
bar.append("text")
.attr("x", x.rangeBand() + (x.rangeBand()/1.5) )
.attr("y", function(d) { return y(d.gdp) - pxAboveBar ; })
.attr("dy", ".75em")
.text(function(d) { return d.gdp; });
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate("+margin.left+","+ height+")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.attr("transform", "translate("+margin.left+",0)")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("GDP in trillions");
});
</script>
THE JSON
JSON
[
{ "country":"United States",
"gdp":17.4
},
{ "country":"China",
"gdp":10.4
},
{ "country":"Japan",
"gdp":4.6
},
{ "country":"Germany",
"gdp":3.9
},
{ "country":"United Kingdom",
"gdp":2.9
},
{ "country":"France",
"gdp":2.8
},
{ "country":"Brazil",
"gdp":2.4
},
{ "country":"Italy",
"gdp":2.1
},
{ "country":"India",
"gdp":2.1
},
{ "country":"Russia",
"gdp":1.9
}
]
Lets Break It Down
让我们分解
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var margin ={top:40, right:40, bottom:40, left:40},
width=900-margin.left - margin.right,
height=500-margin.top-margin.bottom;
To start off you see we call for the d3.js script. Below that we start to write our javascript. We start with a simple javascript object called margin where we set different margins to help us kind of set the display frame for our chart.
首先,您看到我们需要d3.js脚本。 在此之下,我们开始编写我们JavaScript。 我们从名为margin的简单javascript对象开始,在其中我们设置了不同的边距,以帮助我们为图表设置显示框架。
var x = d3.scale.ordinal().rangeRoundBands([0, width], .5);
var y = d3.scale.linear().range([height, 0]);
Next we want to get the length of our x and y axis for the chart. We use ordinal() and linear() here. We are going to set our Y axis to be a linear range between the height of our chart and 0. Note: we start with height so that we display the highest value first then moving down to 0 on the y-axis. Our x axis we will start with 0 and move to our desired width with a little padding. The rangeRoundBands method computes range values so as to divide the chart area into evenly-spaced, evenly-sized bands, as in a bar chart.
接下来,我们要获取图表的x和y轴的长度。 我们在这里使用ordinal()和linear() 。 我们将把Y轴设置为图表高度和0之间的线性范围。注意:我们从高度开始,以便我们首先显示最大值,然后在y轴上向下移动到0。 我们的x轴将从0开始,并通过少许填充移到所需的宽度。 rangeRoundBands方法计算范围值,以便将图表区域划分为均匀分布的,大小均匀的带,如条形图一样。
var chart = d3.select("#chart")
.append("svg") //append svg element inside #chart
.attr("width", width+(2*margin.left)+margin.right)
.attr("height", height+margin.top+margin.bottom);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
d3.select("#chart") looks for the ID of chart within our html much like jquery selectors. Once we find an HTML element with an ID of chart we are going to attach our chart to it. We can use .append() to add our svg elements and we set the .attr() or attributes of width and height for the chart.
d3.select(“#chart”)在html中查找图表ID,就像jquery选择器一样。 一旦找到具有图表IDHTML元素,我们将在图表上附加图表。 我们可以使用.append()添加svg元素,并为图表设置.attr()或width和height的属性。
Next we set our actually svg axises of x and y. We use the .scale() attribute with our linear and ordinal lengths from above. We can also set the x axis to .orient() it horizontally and the y axis to orient it vertically on the left. Technically we are not rendering anything yet, we are just setting up xAxis and yAxis to be used later when we append them to g. Not sure what g is? Well keep reading...
接下来,我们设置x和y的实际svg轴。 我们将.scale()属性与上面的线性和有序长度一起使用。 我们还可以将x轴水平设置为.orient() ,将y轴设置为垂直放置在左侧。 从技术上讲,我们还没有渲染任何东西,我们只是设置xAxis和yAxis,以便稍后在将它们附加到g时使用。 不确定g是多少? 好吧,继续阅读...
d3.json("data.json", function(error, data){
var pxAboveBar = 10;
var ymax = d3.max(d3.values(data));
x.domain(data.map(function(d){ return d.country}));
y.domain([0, ymax.gdp + 2]);
var bar = chart.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i){
return "translate("+x(d.country)+", 0)";
});
Jacob Jenkov's thorough tutorial. Each bar we will be creating consists of a g element. Each g element contains a rect and text. We use the
Jacob Jenkov的详尽教程。 我们将创建的每个条形图均由ag元素组成。 每个g元素都包含一个rect和文本。 我们使用
.data method to populate our data results array and the
.data方法填充数据结果数组,并使用
.enter() to allow us access to each one of them.
.enter()允许我们访问其中的每一个。
Since there is exactly one rect and one text element per g element, we can .append() these elements directly to the g. In a few moments we will append a rect and text that will inherit data from their parent g element, and can use the associated data to determine positions.
由于每个g元素恰好有一个rect和一个text元素,因此我们可以将这些元素直接.append()到g。 稍后,我们将添加一个rect和text,它们将从其父g元素继承数据,并可以使用关联的数据来确定位置。
bar.append("rect")
.attr("y", function(d) {
return y(d.gdp);
})
.attr("x", function(d,i){
return x.rangeBand();
})
.attr("height", function(d) {
return height - y(d.gdp);
})
.attr("width", x.rangeBand());
bar.append("text")
.attr("x", x.rangeBand() + (x.rangeBand()/1.5) )
.attr("y", function(d) { return y(d.gdp) - pxAboveBar ; })
.attr("dy", ".75em")
.text(function(d) { return d.gdp; });
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate("+margin.left+","+ height+")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.attr("transform", "translate("+margin.left+",0)")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("GDP in trillions");
.attr("transform", "translate") can provide us with the exact coordinates and the
.attr(“ transform”,“ translate”)可以为我们提供确切的坐标,并为
.call() method to pass in our current selection. The y axis is almost the same except that we want to add some text or a label to the y axis, indicating that it is GDP in trillions to help the user understand each of the values.
.call()方法提供当前选择。 y轴几乎相同,只是我们要在y轴上添加一些文本或标签,以表示它是GDP的万亿美元,以帮助用户理解每个值。
This was just a quick walkthrough of a bar chart using potentially dynamic data. Hopefully if nothing else it has exposed you to some of the d3.js API's, numerous examples and more information regarding SVG's.
这只是使用潜在动态数据的条形图的快速演练。 希望它能使您接触到一些 d3.js API , 众多示例以及有关SVG的更多信息。
You can download the attached d3.zip to see it all in one place and run it yourself.
您可以下载附件的d3.zip ,将其放在一个地方查看并自己运行。
You can also see a picture of the final product below...
您还可以在下面看到最终产品的图片...
![final.jpg](https://i-blog.csdnimg.cn/blog_migrate/7374b788d5df5d313ae6dfa700cb9ffe.png)
翻译自: https://www.experts-exchange.com/articles/20779/Data-Visualizations-in-d3-js.html
d3.js 数据可视化负数