Shiny中ggplotly调用geom_col报x/y美学映射缺失错误求助
解决Shiny中ggplot+plotly组合绘图时的geom_col美学映射错误
问题描述
作为Shiny/shinydashboard新手,在学习项目中使用plotly结合geom_bar或geom_col绘图时,明明已在ggplot()中指定x和y美学映射,却仍收到错误提示。在flexdashboard中也遇到同类问题,但非plotly的常规ggplot绘图均可正常运行。
测试数据
df2 <- data.frame (Loc = c("Los Angeles", "New York City", "Seattle"), n = c(337, 233, 304)) df2 <- as.tibble(df2)
测试代码
header <- dashboardHeader(title="Employee Dashboard") sidebar <- dashboardSidebar() body <- dashboardBody( fluidRow( box( plotlyOutput("loc_plot")) ) ) ui <- dashboardPage(header, sidebar, body) server <- function(input, output, session) { output$loc_plot <- renderPlotly({ loc_plotly <- df2 %>% ggplot(aes(x=Loc, y=n)) + geom_col(fill= "#2171B5") ggplotly(loc_plotly) }) } shinyApp(ui=ui, server=server)
错误信息
geom_col() 需要以下缺失的美学映射:x 和 y
排查思路
- 检查包版本冲突:plotly与ggplot2版本不兼容可能引发此类问题,建议更新至最新稳定版:
update.packages(c("ggplot2", "plotly", "shiny", "shinydashboard")) - 确认数据的作用域:确保
df2在server函数的环境中可访问。可以尝试在renderPlotly内重新定义数据,或把数据放在global.R文件中加载。 - 显式传递美学映射给geom_col:避免ggplot继承美学映射时出现异常,显式为geom_col指定数据和映射:
loc_plotly <- ggplot(df2, aes(x=Loc, y=n)) + geom_col(data=df2, aes(x=Loc, y=n), fill= "#2171B5") - 排除tibble格式影响:注释掉
df2 <- as.tibble(df2),使用原始data.frame测试是否正常。 - 简化代码结构:去掉管道符,改用常规写法测试:
loc_plotly <- ggplot(df2, aes(x=Loc, y=n)) + geom_col(fill= "#2171B5") - 分步验证:先在Shiny环境外运行基础ggplot代码,确认能生成正常图形,再用
ggplotly转换,最后嵌入renderPlotly:# 第一步:验证基础ggplot loc_plot <- ggplot(df2, aes(x=Loc, y=n)) + geom_col(fill= "#2171B5") print(loc_plot) # 第二步:验证plotly转换 loc_plotly <- ggplotly(loc_plot) print(loc_plotly)
内容的提问来源于stack exchange,提问作者Catherine Dalton
相关产品推荐
相关产品推荐

