我正在尝试利用在SO上找到的ggplot代码。问题是我不断收到错误,我认为这与尝试通过Shinydashboard传递功能有关。我已经尝试过各种方法。我可以在控制台中正常渲染,但不能在Shinydashboard中渲染。
library(shinydashboard)
library(shiny)
library(ggplot2)
library(dplyr)
ui <- fluidPage(
gggauge(52,breaks=c(0,35,70,100)
)
)
server <- function(input, output) {
gggauge <- function(pos,breaks=c(0,30,70,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=100)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="red")+
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold")+geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="forestgreen")+
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y))+
geom_text(data=as.data.frame(breaks), size=5, fontface="bold", vjust=0,
aes(x=1.1*cos(pi*(1-breaks/100)),y=1.1*sin(pi*(1-breaks/100)),label=paste0(breaks,"%")))+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
}
shinyApp(ui = ui, server = server)
答案 0 :(得分:0)
使用-
library(shinydashboard)
library(shiny)
library(ggplot2)
library(dplyr)
gggauge <- function(pos,breaks=c(0,30,70,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=100)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="red")+
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold")+geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="forestgreen")+
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y))+
geom_text(data=as.data.frame(breaks), size=5, fontface="bold", vjust=0,
aes(x=1.1*cos(pi*(1-breaks/100)),y=1.1*sin(pi*(1-breaks/100)),label=paste0(breaks,"%")))+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
ui <- fluidPage(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
server <- function(input, output) {
output$plot1 <- renderPlot({
#plot(mtcars$wt, mtcars$mpg)
gggauge(52,breaks=c(0,35,70,100))
})
}
shinyApp(ui = ui, server = server)
输出
说明
您混合了一些东西,但是您几乎在那儿。您需要的一切都在这里。您只需要组织。让我们看一下这些组件-
gggauge
是一种绘制图表的函数,因此它需要是一个单独定义的函数,并且从服务器组件中被调用。仅在server
对象中定义它是不够的。在您的情况下,该函数正在被定义,而不是被调用!ui
组件需要一个占位符以渲染图。直接尝试在ui
中渲染图不会削减它。您只需要在其中充当占位符(UI组件)的plotOutput
对象server
函数在gggauge
对象中绘制图形了。希望能帮上忙!