使用GoogleVis的R中的Sankey图

时间:2018-12-03 18:40:06

标签: r googlevis

这是我的虚拟数据:

df <- data.frame(First_Area=c('group1', 'group1', 'group1', 'group2', 'group2', 'group2', 'group2', 'group3', 'group3', 'group3', 'group3', 'group3', 'group4', 'group4', 'group4', 'group4', 'group5', 'group5', 'group5', 'group5', 'group6', 'group6', 'group6', 'group7', 'group7', 'group8', 'group8', 'group8', 'group8', 'group8', 'group9', 'group9', 'group9', 'group10', 'group10', 'group10', 'group11', 'group11', 'group11'), record_count=c(25000, 25000, 25000, 5555, 5555, 5555, 8335, 5556, 5556, 5556, 5556, 2776, 5555, 5555, 5555, 5555, 2500, 2500, 500, 55, 1851, 1851, 1853, 5000, 555, 1100, 500, 1500, 1500, 956, 1852, 1852, 1852, 1852, 1852, 1852, 1852, 1852, 1852), Second_Area=c('group2', 'group3', 'group12', 'group13', 'group5', 'group6', 'group7', 'group8', 'group9', 'group10', 'group11', 'group14', 'group15', 'group16', 'group17', 'group18', 'group19', 'group20', 'group21', 'group22', 'group23', 'group24', 'group25', 'group26', 'group27', 'group28', 'group29', 'group30', 'group31', 'group32', 'group33', 'group34', 'group35', 'group36', 'group37', 'group38', 'group39', 'group40', 'group41'))

我尝试使用以下代码在Googlevis上创建一个sankey图:

plot(
  gvisSankey(df, from="First_Area", 
             to="Second_Area", weight="record_count",
             options=list(
               height=1250,
               sankey="{link:{color:{fill:'lightblue'}}}"
               ))
)

,我不断收到此错误 数据表中的格式无效:列#1必须为“字符串”类型

我尝试将第一个和第二个区域转换为一个因子和一个字符,但仍然遇到相同的错误。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

难以置信,但是您需要更改数据框中列的顺序。

数据

df <- data.frame(First_Area=c('group1', 'group1', 'group1', 'group2', 'group2', 'group2', 'group2', 'group3', 'group3', 'group3', 'group3', 'group3', 'group4', 'group4', 'group4', 'group4', 'group5', 'group5', 'group5', 'group5', 'group6', 'group6', 'group6', 'group7', 'group7', 'group8', 'group8', 'group8', 'group8', 'group8', 'group9', 'group9', 'group9', 'group10', 'group10', 'group10', 'group11', 'group11', 'group11'), Second_Area=c('group2', 'group3', 'group12', 'group13', 'group5', 'group6', 'group7', 'group8', 'group9', 'group10', 'group11', 'group14', 'group15', 'group16', 'group17', 'group18', 'group19', 'group20', 'group21', 'group22', 'group23', 'group24', 'group25', 'group26', 'group27', 'group28', 'group29', 'group30', 'group31', 'group32', 'group33', 'group34', 'group35', 'group36', 'group37', 'group38', 'group39', 'group40', 'group41'), record_count=c(25000, 25000, 25000, 5555, 5555, 5555, 8335, 5556, 5556, 5556, 5556, 2776, 5555, 5555, 5555, 5555, 2500, 2500, 500, 55, 1851, 1851, 1853, 5000, 555, 1100, 500, 1500, 1500, 956, 1852, 1852, 1852, 1852, 1852, 1852, 1852, 1852, 1852))

代码

plot(
    googleVis::gvisSankey(df, from="First_Area", 
               to="Second_Area", weight="record_count",
               options=list(
                   height=1250,
                   sankey="{link:{color:{fill:'lightblue'}}}"
               ))
)

结果

1