[英]Units in 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)。 如何在图表中显示值和单位?
在sankeyPlot输出的SVG 克元件与类=“节点”创建。 在该元素中, 值及其单位被添加到表示节点的rect元素内的title元素中 。 该标题元素不是可见元素。 另一方面,该名称已添加到文本元素中(在本例中为“ warm”),并且可见。
通过右键单击Rstudio中的视图窗口,然后“检查”,可以看到此结构。
一个快速的解决将是价值和其单位加入到这个文本元素。 这是通过从以下位置替换layout / charts.html中的第105行来完成的:
.text(function (d) { return d.name; })
与
.text(function (d) { return d.name + " " + format(d.value); })
然后使用它作为模板。
当然,可能有更好的解决方案。 我认为title元素由于某种原因而存在(也许在mouseover事件中使用它)。 但这至少是一个开始。 希望对您有所帮助。
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>
")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.