使重叠的 d3.js 雷达图元素透明

Posted

技术标签:

【中文标题】使重叠的 d3.js 雷达图元素透明【英文标题】:Make overlapping d3.js radar chart elements transparent 【发布时间】:2018-01-08 06:38:36 【问题描述】:

如何使 d3.js 雷达图中的重叠部分透明

下面的雷达图 blob 是使用 d3.js 创建的。红色和绿色相交的空间应该是透明的(这将用于比较之前的 之后)。图表下方的 sn-p 包含用于创建雷达图表的代码。为简单起见,我没有包括 5 个轴:

/* Original radar chart design created by Nadieh Bremer - VisualCinnamon.com */
			
	////////////////////////// Data ////////////////////////////// 

	var data = [
				[//Before - red
				axis:"First",value:0.49,
				axis:"Banana",value:0.79,
				axis:"Scratch",value:0.70,
				axis:"Wheelie",value:0.09,
				axis:"Pantalon",value:0.37,
				],[//After - green
				axis:"First",value:0.64,
				axis:"Banana",value:0.44,
				axis:"Scratch",value:0.37,
				axis:"Wheelie",value:0.84,
				axis:"Pantalon",value:0.81,
				]
			];
      
	//////////////////////// Setup //////////////////////////////// 

	var margin = top: 50, right: 50, bottom: 50, left: 50,
      width = 300,
		  height = 300;
	var color = d3.scale.ordinal().range(["#CC333F","#53e87d"]);
	var radarChartOptions = 
		w: width,				//Width of the circle
		h: height,				//Height of the circle
		margin: margin, 		//The margins of the SVG
		opacityArea: 0.7, 	//The opacity of the area of the blob
		color: color	//Color function
	;

	//////////////////////// RadarChart ///////////////////////////
  
	RadarChart("#radarChart1", data, radarChartOptions);

/////////////////////////////////////////////////////////
/////////////// The Radar Chart Function ////////////////
/////////////// Written by Nadieh Bremer ////////////////
////////////////// VisualCinnamon.com ///////////////////
/////////// Inspired by the code of alangrafu ///////////
/////////////////////////////////////////////////////////

function RadarChart(id, data, options) 
	
	/////////////////////////////////////////////////////////
	///////////////     Prep                 ////////////////
  /////////////////////////////////////////////////////////

	var cfg = radarChartOptions;
	var allAxis = (data[0].map(function(i, j)return i.axis)),	//Names of each axis
		  total = allAxis.length,					            //The number of different axes
		  radius = Math.min(cfg.w/2, cfg.h/2), 	      //Radius of the outermost circle
		  Format = d3.format('%'),			              //Percentage formatting
		  angleSlice = Math.PI * 2 / total;	          //The width in radians of each "slice"
	var rScale = d3.scale.linear()                  //Scale for the radius
		           .range([0, radius]);
		

	//////////// Create the container SVG and g /////////////
  
	var svg = d3.select(id).append("svg") 	//Initiate the radar chart SVG
			.attr("width",  cfg.w + cfg.margin.left + cfg.margin.right)
			.attr("height", cfg.h + cfg.margin.top + cfg.margin.bottom)
			.attr("class", "radar"+id);
	var g = svg.append("g") 	//Append a g element	
			.attr("transform", "translate(" + (cfg.w/2 + cfg.margin.left) + "," + (cfg.h/2 + cfg.margin.top) + ")");
			


	/////////////////////////////////////////////////////////
	///////////// Draw the radar chart blobs ////////////////
	/////////////////////////////////////////////////////////
	
	//The radial line function
	var radarLine = d3.svg.line.radial()
		.interpolate("cardinal-closed")
		.radius(function(d)  return rScale(d.value); )
		.angle(function(d,i) 	return i*angleSlice; );


	//Create a wrapper for the blobs	
	var blobWrapper = g.selectAll(".radarWrapper")
		.data(data)
		.enter().append("g")
		.attr("class", "radarWrapper");
			
	//Append the backgrounds	
	blobWrapper
		.append("path")
		.attr("class", "radarArea")
		.attr("d", function(d,i)  return radarLine(d); )
		.style("fill", function(d,i)  return cfg.color(i);)
		.style("fill-opacity", cfg.opacityArea);
	
	
//RadarChart function
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- Radar Chart -->
<div class="radar-chart" id="radarChart1"></div>

我发现在 html5-Canvas 中重叠的元素可以变成透明的 (1)。它还可以用于将 d3 节点绑定到它 (2),并且它们可以通过这种方式变得透明。然而,对于像上面的雷达图斑点这样的更复杂的对象,这似乎非常复杂。在d3中有一个简单的解决方案吗? (chart.js中好像有(3))

附录 - 我已经找到的内容:

    通过将globalCompositeOperation 模式设置为'xor',可以使用HTML5-Canvas 使重叠(非d3)元素透明:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.globalCompositeOperation = 'xor';

// WITHOUT overlap:
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);

ctx.fillStyle = 'red';
ctx.fillRect(110, 50, 100, 100);

// WITH (transparent) overlap:
ctx.fillStyle = 'blue';
ctx.fillRect(250, 10, 100, 100);

ctx.fillStyle = 'red';
ctx.fillRect(300, 50, 100, 100);
<!-- Original from https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation -->

<style>
  body 
    background-image: url("http://www.scri8e.com/stars/PNG_Clouds/zc06.png?filename=./zc06.png");

</style>

<canvas id="canvas"   ></canvas>

    d3.js 节点也可以通过 HTML5-Canvas 使用 getContext("2d") 进行可视化。可以按照与上述 (1) 相同的方式实现重叠。但是,据我了解,这需要 重新创建 javascript 中的每个元素,然后在其上绑定 d3 数据。例如对于圆形,必须在 HTML5-Canvas 上下文中重新创建弧元素,如 this example by Mike Bostock:

    context = canvas.getContext("2d"); ...
    
    context.arc(element.getAttribute("x"), element.getAttribute("y"), element.getAttribute("radius"), 0, 2 * Math.PI);
    

    这是chartjs 中可能的实现(见下图)

【问题讨论】:

这可能会有所帮助:"What is the best approach for overlapping SVG elements area fill?". 【参考方案1】:

您的描述暗示您将始终有两个图表(“之前 -> 之后”)。

此解决方案使用 SVG 蒙版。虽然它可以使用更多图表,但它变得更加复杂。您必须动态构造 &lt;mask&gt; 元素。

/* Original radar chart design created by Nadieh Bremer - VisualCinnamon.com */
        
////////////////////////// Data ////////////////////////////// 

var data = [
    [//Before - red
    axis:"First",value:0.49,
    axis:"Banana",value:0.79,
    axis:"Scratch",value:0.70,
    axis:"Wheelie",value:0.09,
    axis:"Pantalon",value:0.37,
    ],[//After - green
    axis:"First",value:0.64,
    axis:"Banana",value:0.44,
    axis:"Scratch",value:0.37,
    axis:"Wheelie",value:0.84,
    axis:"Pantalon",value:0.81,
    ]
];
      
//////////////////////// Setup //////////////////////////////// 

var margin = top: 50, right: 50, bottom: 50, left: 50,
    width = 300,
    height = 300;
var color = d3.scale.ordinal().range(["#CC333F","#53e87d"]);
var radarChartOptions = 
    w: width,                //Width of the circle
    h: height,                //Height of the circle
    margin: margin,         //The margins of the SVG
    opacityArea: 0.7,     //The opacity of the area of the blob
    color: color    //Color function
;

//////////////////////// RadarChart ///////////////////////////
  
RadarChart("radarChart", data, radarChartOptions);

function RadarChart(id, data, options) 

    var cfg = radarChartOptions;
    var allAxis = (data[0].map(function(i, j)return i.axis)),    //Names of each axis
        total = allAxis.length,                                //The number of different axes
        radius = Math.min(cfg.w/2, cfg.h/2),           //Radius of the outermost circle
        Format = d3.format('%'),                          //Percentage formatting
        angleSlice = Math.PI * 2 / total;              //The width in radians of each "slice"
    var rScale = d3.scale.linear()                  //Scale for the radius
       .range([0, radius]);
  
    var svg = d3.select('#' + id)     //Initiate the radar chart SVG
        .attr("width",  cfg.w + cfg.margin.left + cfg.margin.right)
        .attr("height", cfg.h + cfg.margin.top + cfg.margin.bottom)
        .attr("class", "radar"+id);

    svg.select('#bg').attr('r', radius);

    var dx = cfg.w/2 + cfg.margin.left,
        dy = cfg.h/2 + cfg.margin.top;

    svg.selectAll('mask')
        .attr('x', -dx)
        .attr('y', -dy);

    var source = svg.select('#radarSource')
    var wrapper = svg.select('#radarWrapper')
        .attr("transform", "translate(" + dx + "," + dy + ")");

    //The radial line function
    var radarLine = d3.svg.line.radial()
        .interpolate("cardinal-closed")
        .radius(function(d)  return rScale(d.value); )
        .angle(function(d,i)     return i*angleSlice; );


    //Draw the blobs    
    source.selectAll("path")
        .data(data)
        .enter().append("path")
        .attr("id", function(d,i) return 'area' + i;)
        .attr("d", function(d,i)  return radarLine(d); );

    //render and apply masks
    wrapper.selectAll("use")
        .data(data)
        .enter().append("use")
        .attr("xlink:href", function(d,i) return '#area' + i;)
        .attr("mask", function(d,i) return 'url(#mask' + i + ')';)
        .style("fill", function(d,i)  return cfg.color(i);)
        .style("fill-opacity", cfg.opacityArea);


//RadarChart function
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- Radar Chart -->
<svg id="radarChart" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <circle id="bg" />
    <g id="radarSource" />
    <mask id="mask0" maskUnits="userSpaceOnUse">
      <use xlink:href="#bg" fill="white" />
      <use xlink:href="#area1" fill="black" />
    </mask>
    <mask id="mask1" maskUnits="userSpaceOnUse">
      <use xlink:href="#bg" fill="white" />
      <use xlink:href="#area0" fill="black" />
    </mask>
  </defs>
  <g id="radarWrapper" />
</svg>

【讨论】:

感谢您的精彩回答!这对我帮助很大! :)

以上是关于使重叠的 d3.js 雷达图元素透明的主要内容,如果未能解决你的问题,请参考以下文章

如何用excel做雷达图

雷达图数据标签在内部显示

使用PHPWord生成图表——雷达图

python画雷达图

如何批量生成每组数据的雷达图?

使用PHPWord生成图表——雷达图