rCharts sankey图中的单位

时间:2016-06-15 15:14:18

标签: javascript r plot rcharts sankey-diagram

我使用以下代码生成rCharts Sankey图表(https://github.com/timelyportfolio/rCharts_d3_sankey):

if(!require(rCharts)){
  library(devtools)
  install_github('ramnathv/rCharts')
}
library(rCharts)

sankeyPlot <- rCharts$new()
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot$set(
  data = data.frame(source=c('Cold','Warm','Total'),target=c('Total','Total','End'),value=c(20,80,100)),
  nodeWidth = 15,
  nodePadding = 10,
  layout = 32,
  width = 500,
  height = 300,
  units = "TWh",
  labelFormat = ".1%"
)
sankeyPlot$setTemplate(
  afterScript = "
  <script>
  // to be specific in case you have more than one chart
  d3.selectAll('#{{ chartId }} svg path.link')
  .style('stroke', function(d){
  //here we will use the source color
  //if you want target then sub target for source
  //or if you want something other than gray
  //supply a constant
  //or use a categorical scale or gradient
  return d.source.color;
  })
  //note no changes were made to opacity
  //to do uncomment below but will affect mouseover
  //so will need to define mouseover and mouseout
  //happy to show how to do this also
  // .style('stroke-opacity', .7)
  </script>
  ")

sankeyPlot

Sankeyplot$set中,我为单位设置了一个值。但是,我既没有看到单位,也没有看到值。单元示例来自官方github文档(example_hirst_f1.R)。如何在图表中显示值和单位?

Before changes

2 个答案:

答案 0 :(得分:1)

在sankeyPlot输出中,使用class =“node”创建svg g 元素。在此元素中,值及其单位将添加到表示节点的 rect 元素内的 title 元素中。此标题元素不是可见元素。另一方面,名称添加在文本元素中(在本例中为“暖色”)并且可见。

您可以通过右键单击Rstudio中的视图窗口然后“检查”来查看此结构。

Screenshot of the node structure in Web Inspector

快速解决方法是将值及其单位添加到此文本元素中。 这是通过替换

中layout / charts.html中的第105行来完成的
  .text(function (d) { return d.name; })

.text(function (d) { return d.name + " " + format(d.value); })

然后将其用作模板。

当然可能有更好的解决方案。我想标题元素是出于某种原因(可能在鼠标悬停事件中使用它)。但至少这是一个开始。我希望它有所帮助。

答案 1 :(得分:0)

JeroenDM的答案也可以插入到后记中。在这种情况下,可以不加修改地使用Github存储库。

sankeyPlot$setTemplate(
  afterScript = "
  <script>
  // to be specific in case you have more than one chart
  d3.selectAll('#{{ chartId }} svg path.link')
  .style('stroke', function(d){
  //here we will use the source color
  //if you want target then sub target for source
  //or if you want something other than gray
  //supply a constant
  //or use a categorical scale or gradient
  return d.source.color;
  })
  //note no changes were made to opacity
  //to do uncomment below but will affect mouseover
  //so will need to define mouseover and mouseout
  //happy to show how to do this also
  // .style('stroke-opacity', .7)

  units = ' TWh'

  var formatNumber = d3.format('0,.0f'),    // zero decimal places
  format = function(d) { return formatNumber(d) + units; }

  d3.selectAll('#{{ chartId }} svg .node text')
  .text(function (d) { return d.name + ' (' + format(d.value) + ')'; })
  </script>
  ")

After the changes