Javascript 结合D3可视化

Javascript 结合D3可视化,javascript,html,css,d3.js,Javascript,Html,Css,D3.js,我试图结合两个D3可视化。我以前发现了一个问题,但它并没有真正的解决办法 当我合并这两个文件时,可视化重叠并产生以下结果: streamgraph组件: <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .chart { background: #fff; } p {

我试图结合两个D3可视化。我以前发现了一个问题,但它并没有真正的解决办法

当我合并这两个文件时,可视化重叠并产生以下结果:

streamgraph组件:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
    body {
        font: 10px sans-serif;
    }
    .chart {
        background: #fff;
    }
    p {
        font: 12px helvetica;
    }
    .axis path, .axis line {
        fill: none;
        stroke: #000;
        stroke-width: 2px;
        shape-rendering: crispEdges;
    }
    button {
        position: absolute;
        right: 50px;
        top: 10px;
    }
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>


<div class="chart">
</div>

<script>
    chart("Data.csv", "blue");
    var datearray = [];
    var colorrange = [];
    function chart(csvpath, color) {
        if (color == "blue") {
            colorrange = ["#045A8D", "#2B8CBE", "#74A9CF", "#A6BDDB", "#D0D1E6", "#F1EEF6"];
        }
        else if (color == "pink") {
            colorrange = ["#980043", "#DD1C77", "#DF65B0", "#C994C7", "#D4B9DA", "#F1EEF6"];
        }
        else if (color == "orange") {
            colorrange = ["#B30000", "#E34A33", "#FC8D59", "#FDBB84", "#FDD49E", "#FEF0D9"];
        }
        strokecolor = colorrange[0];
        var format = d3.time.format("%m/%d/%y");
        var margin = {top: 20, right: 40, bottom: 30, left: 50};
        var width = document.body.clientWidth - margin.left - margin.right;
        var height = 400 - margin.top - margin.bottom;
        var tooltip = d3.select("body")
                .append("div")
                .attr("class", "remove")
                .style("position", "absolute")
                .style("z-index", "20")
                .style("visibility", "hidden")
                .style("top", "30px")
                .style("left", "75px");
        var x = d3.time.scale()
                .range([0, width]);
        var y = d3.scale.linear()
                .range([height-10, 0]);
        var z = d3.scale.ordinal()
                .range(colorrange);
        var xAxis = d3.svg.axis()
                .orient("bottom")
                .scale(x)
                .ticks(d3.time.years, 10); //tick on every 10 years
        /*.scale(x)
         .orient("bottom")
         .text(date)
         //;*/
        //. tickFormat(x)
        //. tickValues(date)
        //was already there but out of view -> changed the left margin
        var yAxis = d3.svg.axis()
                .scale(y);
        var stack = d3.layout.stack()
                .offset("silhouette")
                .values(function(d) { return d.values; })
                .x(function(d) { return d.date; })
                .y(function(d) { return d.value; });
        var nest = d3.nest()
                .key(function(d) { return d.key; });
        var area = d3.svg.area()
                .interpolate("cardinal")
                .x(function(d) { return x(d.date); })
                .y0(function(d) { return y(d.y0); })
                .y1(function(d) { return y(d.y0 + d.y); });
        var svg = d3.select(".chart").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        /* correct this function
         var graph = d3.csv(csvpath, function(data) {
         data.forEach(function(d) {
         d.date = format.parse(d.date);
         d.value = +d.value;
         });*/
        var graph = d3.csv(csvpath, function(raw) {
            var data = [];
            raw.forEach(function (d) {
                data.push({
                    key: d.Country,
                    date : new Date(1980,0,1), //I had a bug in creating the right dates
                    value : parseInt(d['1980-1989'].replace(',','')) //get rid of the thousand separator
                });
                data.push({
                    key: d.Country,
                    date : new Date(1990,0,1),
                    value : parseInt(d['1990-1999'].replace(',',''))
                });
                data.push({
                    key: d.Country,
                    date : new Date(2000,0,1),
                    value : parseInt(d['2000-2009'].replace(',','') )
                });
            });
            var layers = stack(nest.entries(data));
            x.domain(d3.extent(data, function(d) { return d.date; }));
            y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
            svg.selectAll(".layer")
                    .data(layers)
                    .enter().append("path")
                    .attr("class", "layer")
                    .attr("d", function(d) { return area(d.values); })
                    .style("fill", function(d, i) { return z(i); });
            //adding .text causes axis to dissapear
            svg.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                //.text(date)
                    .call(xAxis);
            svg.append("g")
                    .attr("class", "y axis")
                    .attr("transform", "translate(" + width + ", 0)")
                //.text(value)
                    .call(yAxis.orient("right"));
            svg.append("g")
                    .attr("class", "y axis")
                    .call(yAxis.orient("left"));
            var pro;
            svg.selectAll(".layer")
                    .attr("opacity", 1)
                    .on("mouseover", function(d, i) {
                        svg.selectAll(".layer").transition()
                                .duration(250)
                                .attr("opacity", function(d, j) {
                                    return j != i ? 0.6 : 1;
                                })})
                    .on("mousemove", function(d, i) {
                        var mousex = d3.mouse(this);
                        mousex = mousex[0];
                        var invertedx = x.invert(mousex);
                        //find the largest smaller element
                        var dd = d.values.filter(function(d) { return d.date <= invertedx; });
                        dd = dd[dd.length -1]; //use the last element
                        pro = dd.value;
                        d3.select(this)
                                .classed("hover", true)
                                .attr("stroke", strokecolor)
                                .attr("stroke-width", "0.5px");
                        tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "visible");
                    })
                    .on("mouseout", function(d, i) {
                        svg.selectAll(".layer")
                                .transition()
                                .duration(250)
                                .attr("opacity", "1");
                        d3.select(this)
                                .classed("hover", false)
                                .attr("stroke-width", "0px");
                        tooltip.html( "<p>" + d.key + "<br>" + pro + "</p>" ).style("visibility", "hidden");
                    })
            var vertical = d3.select(".chart")
                    .append("div")
                    .attr("class", "remove")
                    .style("position", "absolute")
                    .style("z-index", "19")
                    .style("width", "1px")
                    .style("height", "380px")
                    .style("top", "10px")
                    .style("bottom", "30px")
                    .style("left", "0px")
                    .style("background", "#fff");
            d3.select(".chart")
                    .on("mousemove", function(){
                        var mousex = d3.mouse(this);
                        mousex = mousex[0] + 5;
                        vertical.style("left", mousex + "px" )})
                    .on("mouseover", function(){
                        var mousex = d3.mouse(this);
                        mousex = mousex[0] + 5;
                        vertical.style("left", mousex + "px")});
        });
    }
</script>
<!DOCTYPE html>
<meta charset="utf-8">
<title>U.S Immigration Data Visualization</title>
<style>
.country:hover{
  stroke: #fff;
  stroke-width: 1.5px;
}
.text{
  font-size:10px;
  text-transform:capitalize;
}
#container {
    margin: 10px 10%;
    border:2px solid #000;
  border-radius: 5px;
  height:100%;
  overflow:hidden;
  background: #e1eafe;
}
.hidden { 
  display: none; 
}
div.tooltip {
  color: #222; 
  background: #fff; 
  padding: .5em; 
  text-shadow: #f5f5f5 0 1px 0;
  border-radius: 2px; 
  box-shadow: 0px 0px 2px 0px #a6a6a6; 
  opacity: 0.9; 
  position: absolute;
}
.graticule {
  fill: none;
  stroke: #bbb;
  stroke-width: .5px;
  stroke-opacity: .5;
}
.equator {
  stroke: #ccc;
  stroke-width: 1px;
}

</style>
</head>
<br>

  <h1><center>U.S Immigration Data Visualization</center></h1>
  <h2><b>Work in Progress</b></h2>
  <h3><b>Ex-USSR countries included in Russia</b></h3>
  <h3><b>Ex-Yugoslavia included in Macedonia</b></h3>


  <div id="container"></div>

<script src="js/d3.min.js"></script>
<script src="js/topojson.v1.min.js"></script>
  <script src="http://d3js.org/d3.geo.tile.v0.min.js"></script>
<script>
d3.select(window).on("resize", throttle);

var zoom = d3.behavior.zoom()
    .scaleExtent([1, 9])
    .on("zoom", move);


var width = document.getElementById('container').offsetWidth;
var height = width / 2;

var topo,projection,path,svg,g;

var graticule = d3.geo.graticule();

var tooltip = d3.select("#container").append("div").attr("class", "tooltip hidden");

setup(width,height);

function setup(width,height){
  projection = d3.geo.mercator()
    .translate([(width/2), (height/2)])
    .scale( width / 2 / Math.PI);

  path = d3.geo.path().projection(projection);

  svg = d3.select("#container").append("svg")
      .attr("width", width)
      .attr("height", height)
      .call(zoom)
      .on("click", click)
      .append("g");

  g = svg.append("g");

}

d3.json("data/world-topo-min.json", function(error, world) {

  var countries = topojson.feature(world, world.objects.countries).features;

  topo = countries;
  draw(topo);

});

function draw(topo) {

  svg.append("path")
     .datum(graticule)
     .attr("class", "graticule")
     .attr("d", path);


  g.append("path")
   .datum({type: "LineString", coordinates: [[-180, 0], [-90, 0], [0, 0], [90, 0], [180, 0]]})
   .attr("class", "equator")
   .attr("d", path);


  var country = g.selectAll(".country").data(topo);

  country.enter().insert("path")
      .attr("class", "country")
      .attr("d", path)
      .attr("id", function(d,i) { return d.id; })
      .attr("title", function(d,i) { return d.properties.name; })
      .style("fill", function(d, i) { return d.properties.color; });

  //offsets for tooltips
  var offsetL = document.getElementById('container').offsetLeft+20;
  var offsetT = document.getElementById('container').offsetTop+10;

  //tooltips
  country
    .on("mousemove", function(d,i) {

      var mouse = d3.mouse(svg.node()).map( function(d) { return parseInt(d); } );

      tooltip.classed("hidden", false)
             .attr("style", "left:"+(mouse[0]+offsetL)+"px;top:"+(mouse[1]+offsetT)+"px")
             .html(d.properties.name);

      })
      .on("mouseout",  function(d,i) {
        tooltip.classed("hidden", true);
      }); 


  //EXAMPLE: adding some capitals from external CSV file
  d3.csv("Data.csv", function(err, capitals) {

   capitals.forEach(function(i){
     addpoint(i.CapitalLongitude, i.CapitalLatitude );
    });

  });

}


function redraw() {
  width = document.getElementById('container').offsetWidth;
  height = width / 2;
  d3.select('svg').remove();
  setup(width,height);
  draw(topo);
}


function move() {

  var t = d3.event.translate;
  var s = d3.event.scale; 
  zscale = s;
  var h = height/4;


  t[0] = Math.min(
    (width/height)  * (s - 1), 
    Math.max( width * (1 - s), t[0] )
  );

  t[1] = Math.min(
    h * (s - 1) + h * s, 
    Math.max(height  * (1 - s) - h * s, t[1])
  );

  zoom.translate(t);
  g.attr("transform", "translate(" + t + ")scale(" + s + ")");

  //adjust the country hover stroke width based on zoom level
  d3.selectAll(".country").style("stroke-width", 1.5 / s);

}



var throttleTimer;
function throttle() {
  window.clearTimeout(throttleTimer);
    throttleTimer = window.setTimeout(function() {
      redraw();
    }, 200);
}


//geo translation on mouse click in map
function click() {
  var latlon = projection.invert(d3.mouse(this));
  console.log(latlon);
}


//function to add points and text to the map (used in plotting capitals)
function addpoint(lat,lon,text) {

  var gpoint = g.append("g").attr("class", "gpoint");
  var x = projection([lat,lon])[0];
  var y = projection([lat,lon])[1];

  gpoint.append("svg:circle")
        .attr("cx", x)
        .attr("cy", y)
        .attr("class","point")
        .attr("r", 1);

  //conditional in case a point has no associated text
  //if(text.length>0){

  //  gpoint.append("text")
 //         .attr("x", x+2)
 //         .attr("y", y+2)
 //         .attr("class","text")
  //        .text(text);
  //}

}

</script>
</body>
</html>

身体{
字体:10px无衬线;
}
.图表{
背景:#fff;
}
p{
字体:12px helvetica;
}
.轴路径,.轴线{
填充:无;
行程:#000;
笔画宽度:2px;
形状渲染:边缘清晰;
}
钮扣{
位置:绝对位置;
右:50px;
顶部:10px;
}
图表(“Data.csv”、“蓝色”);
var datearray=[];
var colorrange=[];
功能图(csvpath,彩色){
如果(颜色=“蓝色”){
颜色范围=[“045A8D”、“2B8CBE”、“74A9CF”、“A6BDDB”、“D0D1E6”、“F1EEF6”];
}
否则如果(颜色=“粉色”){
颜色范围=[“980043”、“DD1C77”、“DF65B0”、“C994C7”、“D4B9DA”、“F1EEF6”];
}
else if(颜色=“橙色”){
颜色范围=[“B30000”、“E34A33”、“FC8D59”、“FDBB84”、“FDD49E”、“FEF0D9];
}
strokecolor=颜色范围[0];
var format=d3.time.format(“%m/%d/%y”);
var-margin={顶部:20,右侧:40,底部:30,左侧:50};
var width=document.body.clientWidth-margin.left-margin.right;
变量高度=400-margin.top-margin.bottom;
变量工具提示=d3。选择(“主体”)
.附加(“div”)
.attr(“类”、“删除”)
.style(“位置”、“绝对”)
.风格(“z指数”、“20”)
.style(“可见性”、“隐藏”)
.样式(“顶部”、“30px”)
.样式(“左”、“75px”);
var x=d3.time.scale()
.范围([0,宽度]);
变量y=d3.scale.linear()
.范围([高度-10,0]);
var z=d3.scale.ordinal()
.范围(颜色范围);
var xAxis=d3.svg.axis()
.orient(“底部”)
.比例(x)
.ticks(d3.time.years,10);//每10年打一次勾
/*.比例(x)
.orient(“底部”)
.文本(日期)
//;*/
//.格式(x)
//.日期
//已经存在,但看不见->更改了左边距
var yAxis=d3.svg.axis()
.比例(y);
var stack=d3.layout.stack()
.偏移量(“轮廓”)
.values(函数(d){返回d.values;})
.x(函数(d){返回d.date;})
.y(函数(d){返回d.value;});
var nest=d3.nest()
.key(函数(d){返回d.key;});
var area=d3.svg.area()
.插入(“基数”)
.x(函数(d){返回x(d.date);})
.y0(函数(d){返回y(d.y0);})
.y1(函数(d){返回y(d.y0+d.y);});
var svg=d3。选择(“.chart”)。追加(“svg”)
.attr(“宽度”,宽度+边距。左侧+边距。右侧)
.attr(“高度”,高度+边距。顶部+边距。底部)
.附加(“g”)
.attr(“转换”、“平移”(+margin.left+)、“+margin.top+”);
/*更正此功能
变量图=d3.csv(csvpath,函数(数据){
data.forEach(函数(d){
d、 日期=format.parse(d.date);
d、 值=+d.值;
});*/
var-graph=d3.csv(csvpath,函数(原始){
var数据=[];
原始forEach(函数(d){
数据推送({
关键词:d.国家,
日期:新日期(1980,0,1),//我在创建正确的日期时遇到了一个错误
value:parseInt(d['1980-1989'].replace(',','')//去掉千位分隔符
});
数据推送({
关键词:d.国家,
日期:新日期(1990,0,1),
值:parseInt(d['1990-1999'].替换(',','')
});
数据推送({
关键词:d.国家,
日期:新日期(2000,0,1),
值:parseInt(d['2000-2009'].替换(',','')
});
});
var层=堆栈(nest.entries(data));
x、 域(d3.extent(数据,函数(d){返回d.date;}));
y、 域([0,d3.max(数据,函数(d){返回d.y0+d.y;})];
svg.selectAll(“.layer”)
.数据(图层)
.enter().append(“路径”)
.attr(“类”、“层”)
.attr(“d”,函数(d){返回区域(d.values);})
.style(“fill”,函数(d,i){返回z(i);});
//添加.text会导致轴消失
svg.append(“g”)
.attr(“类”、“x轴”)
.attr(“变换”、“平移(0)”、“高度+”)
//.文本(日期)
.呼叫(xAxis);
svg.append(“g”)
.attr(“类”、“y轴”)
.attr(“变换”、“平移”(+width+),0)
//.文本(值)
.call(yAxis.orient(“右”);
svg.append(“g”)
.attr(“类”、“y轴”)
.呼叫(yAxis.orient(“左”);
var-pro;
svg.selectAll(“.layer”)
.attr(“不透明度”,1)
.on(“鼠标悬停”,功能(d,i){
svg.selectAll(“.layer”).transition()
.持续时间(250)
.attr(“不透明度”,函数(d,j){
返回j!=i?0.6:1;
})})
.on(“mousemove”,函数(d,i){
var mousex=d3.mouse(this);
mousex=mousex[0];
<body>
    <div class="chart">
    </div>
    <div id="container">
    </div>

    <script type="text/javascript">

    var width = 300;
    var height = width / 2;

    // Equivalent of streamgraph code...
    var svg_stream = d3.select(".chart")
      .append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("rect")
      ... // rect attributes

    // Equivalent of map code...  
    var svg_map = d3.select("#container")
      .append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("circle")
      ... // circle attributes
    </script>
</body>