簡體   English   中英

rCharts sankey圖中的單位

[英]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中的視圖窗口,然后“檢查”,可以看到此結構。

Web Inspector中的節點結構的屏幕快照

一個快速的解決將是價值和其單位加入到這個文本元素。 這是通過從以下位置替換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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM