R shiny 和 ggplot2:如何使 geom_col 的边框透明?

R shiny and ggplot2: How to make border of geom_col transparent?

我想让 geom_col 的边框透明。仅在使用 ggplot2:

时有效
library(ggplot2)

dataToPlot <- data.frame(Freq = c(0.0000000, 0.7092199, 1.4184397, 2.1276596, 2.8368794), 
                          variable = rep('A',5), value = c(43089.76, 62923.17, 35446.15, 29553.76, 22433.08))

p <- ggplot( dataToPlot , aes(x=Freq, y = value, group = variable   )  ) +  #
  # geom_bar(stat = "bin") fill = variable, 
  geom_col( mapping = aes(col = variable, fill = variable), colour = F,  alpha = 0.2, orientation = "x", position = "dodge") + 
  # scale_linetype(aes(linetype = 0))
  guides(color = FALSE)

dev.new(); p

然而,与 shiny 完全相同的代码给出了错误:"Error: invalid color name 'FALSE'"

library(ggplot2)
library(shiny)

dataToPlot <- data.frame(Freq = c(0.0000000, 0.7092199, 1.4184397, 2.1276596, 2.8368794), 
                          variable = rep('A',5), value = c(43089.76, 62923.17, 35446.15, 29553.76, 22433.08))

ui <- fluidPage( 
  useShinyjs(),
  fluidRow( 
    column(8,
           plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  output$plot <- renderPlotly({
    p <- ggplot( dataToPlot , aes(x=Freq, y = value, group = variable   )  ) +  #
      # geom_bar(stat = "bin") fill = variable, 
      geom_col( mapping = aes(col = variable, fill = variable), colour = F,  alpha = 0.2, orientation = "x", position = "dodge") + 
      # scale_linetype(aes(linetype = 0))
      guides(color = FALSE)

  })
}

shinyApp(ui,server)

我做错了什么?

你犯了一些错误。

首先,您忘记提及您也在使用软件包 shinyjsplotly

其次,您在服务器部分使用 renderPlotly,但在 ui 中调用 plotOutput。正确的是 ui 中的 plotlyOutput,因为你想要一个有情节的图形。

另一件事是:因为你想要一个 plotly 类型的图形,你必须将你的 ggplot 图形 p 转换为 plotly 图形。因此,您应该在服务器部分添加 ggplotly(p)

最后,为了解决边框问题,您应该使用colour = NA而不是colour = FALSE。第二种方法适用于 ggplot2,但不适用于 plotly。我不知道为什么。也许有人可以澄清这一点。

因此,您的代码应如下所示:

library(ggplot2)
library(shiny)
library(shinyjs)
library(plotly)

dataToPlot <- data.frame(Freq = c(0.0000000, 0.7092199, 1.4184397, 2.1276596, 2.8368794),
                         variable = rep('A',5), 
                         value = c(43089.76, 62923.17, 35446.15, 29553.76, 22433.08))

ui <- fluidPage( 
  useShinyjs(),
  fluidRow( 
    column(8,
           plotlyOutput("plot")
    )
  )
)

server <- function(input, output) {
  output$plot <- renderPlotly({
    p <- ggplot(dataToPlot , aes(x=Freq, y = value, group = variable)) +
      geom_col(mapping = aes(col = variable, fill = variable), colour = NA,  alpha = 0.2, orientation = "x", position = "dodge") + 
      guides(color = FALSE)

    ggplotly(p)
  })
}

shinyApp(ui,server)