gpt4 book ai didi

r - 向 rCharts 中的 Sankey 图添加颜色

转载 作者:行者123 更新时间:2023-12-02 04:21:26 25 4
gpt4 key购买 nike

我在 rCharts 中创建了一个桑基图,但有一个问题。如何添加颜色?我想用不同的颜色表示每个节点,这样更容易可视化路径,而不是仅仅看到连接所有内容的相同灰线。代码和输出如下:

    require(rCharts)
require(rjson)

x = read.csv('/Users/<username>/sankey.csv', header=FALSE)

colnames(x) <- c("source", "target", "value")

sankeyPlot <- rCharts$new()

sankeyPlot$set(
data = x,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 500,
height = 300,
units = "TWh",
title = "Sankey Diagram"
)

sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')

sankeyPlot

这是我的图表的样子

enter image description here

非常感谢!

最佳答案

不确定您想要什么颜色,但如果您安装了较新的 rChartsdevtools::install_github("ramnathv/rCharts") ,以下是您如何根据源值使用 demo here 进行着色。 .

require(rCharts)
require(rjson)

x = read.csv('/Users/<username>/sankey.csv', header=FALSE)

colnames(x) <- c("source", "target", "value")

sankeyPlot <- rCharts$new()

sankeyPlot$set(
data = x,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 500,
height = 300,
units = "TWh",
title = "Sankey Diagram"
)

sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')

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

如果您想使用d3.scale.category??()为了提供您的颜色,我假设您也希望对节点矩形进行类似的着色。以下是更改节点和链接颜色的一个示例。

sankeyPlot$setTemplate(
afterScript = "
<script>
var cscale = d3.scale.category20b();

// 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;
return cscale(d.source.name);
})
//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)
d3.selectAll('#{{ chartId }} svg .node rect')
.style('fill', function(d){
return cscale(d.name)
})
.style('stroke', 'none')
</script>
")

sankeyPlot

关于r - 向 rCharts 中的 Sankey 图添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25412223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com