gpt4 book ai didi

r - 在 Shiny 中打印桑基图

转载 作者:行者123 更新时间:2023-12-03 16:05:05 26 4
gpt4 key购买 nike

我创建了一个像这样的桑基图:

#install.packages("networkD3")
library(networkD3)
nodes = data.frame("name" =
c("Retour", # Node 0
"niet tevreden/ontevreden", # Node 1
"fout", # Node 2
"stuk",
"adres",
"verpakking",
"gebroken/glas"))# Node 3
links = as.data.frame(matrix(c(
0, 1, 10, # Each row represents a link. The first number
0, 2, 20, # represents the node being conntected from.
0, 3, 30,
2, 4, 8,
3, 5, 10,
3, 6, 12# the second number represents the node connected to.
),# The third number is the value of the node
byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 30)

工作正常,但是现在我想用这个情节变得 Shiny 。因此做了以下事情:
## app.R ##
library(shinydashboard)

ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(plotOutput("plot1", height = 250))
)
)
)

library(networkD3)
server <- function(input, output) {

histdata <- rnorm(500)

nodes = data.frame("name" =
c("Retour", # Node 0
"niet tevreden/ontevreden", # Node 1
"fout", # Node 2
"stuk",
"adres",
"verpakking",
"gebroken/glas"))# Node 3
links = as.data.frame(matrix(c(
0, 1, 10, # Each row represents a link. The first number
0, 2, 20, # represents the node being conntected from.
0, 3, 30,
2, 4, 8,
3, 5, 10,
3, 6, 12# the second number represents the node connected to.
),# The third number is the value of the node
byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")

output$plot1 <- renderPlot({
sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 30)
})
output$plot2 <- renderPlot({
data <- histdata[seq_len(10)]
hist(data)
})
}

shinyApp(ui, server)

事情是,由于某种原因,Shiny 可以读取桑基图。如果我更改代码:
box(plotOutput("plot1", height = 250))

到:
box(plotOutput("plot2", height = 250))

它正在绘制直方图。所以桑基图似乎有问题。关于是什么原因造成的任何想法?

最佳答案

您应该使用 renderSankeyNetworksankeyNetworkOutput networkD3 中的函数而不是 plotOutputrenderPlot .所以你的数据已经加载,它看起来像......

library(shiny)
library(shinydashboard)
library(networkD3)

ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
sankeyNetworkOutput("plot")
)
)
)

server <- function(input, output) {

output$plot <- renderSankeyNetwork({
sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 30)
})
}

shinyApp(ui, server)

另见 example here

关于r - 在 Shiny 中打印桑基图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48024037/

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