如何将通过plotly转换的ggplot嵌入R Shiny应用或flexdashboard中?
嵌入方法说明
你现有代码生成的是plotly交互式图表对象,分别嵌入flexdashboard和Shiny的操作方法如下:
方法1:嵌入flexdashboard
flexdashboard原生支持plotly等htmlwidget对象,操作步骤:
- 新建R Markdown文档,输出格式选择
flexdashboard::flex_dashboard - 将生成图表的代码放入代码块,直接返回plotly对象即可完成渲染
完整示例代码
--- title: "发展指标气泡图" output: flexdashboard::flex_dashboard --- ```{r init, include=FALSE} # 加载依赖包 library(ggplot2) library(dplyr) library(plotly) library(viridis) library(hrbrthemes) library(gapminder)
2007年全球各国发展指标
# 数据处理与绘图逻辑和原有代码完全一致 data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year) p <- data %>% mutate(gdpPercap=round(gdpPercap,0)) %>% mutate(pop=round(pop/1000000,2)) %>% mutate(lifeExp=round(lifeExp,1)) %>% arrange(desc(pop)) %>% mutate(country = factor(country, country)) %>% mutate(text = paste("国家: ", country, "\n人口(百万): ", pop, "\n预期寿命: ", lifeExp, "\n人均GDP: ", gdpPercap, sep="")) %>% ggplot( aes(x=gdpPercap, y=lifeExp, size = pop, color = continent, text=text)) + geom_point(alpha=0.7) + scale_size(range = c(1.4, 19), name="Population (M)") + scale_color_viridis(discrete=TRUE, guide=FALSE) + theme_ipsum() + theme(legend.position="none") # 直接输出plotly对象即可显示交互式效果 ggplotly(p, tooltip="text")
## 方法2:嵌入Shiny应用 Shiny需要使用plotly提供的专用渲染函数,操作步骤: - UI端调用`plotlyOutput()`声明图表占位位置 - 服务端将绘图逻辑放入`renderPlotly()`中,返回plotly对象 ### 完整可运行示例代码 ```r library(shiny) library(ggplot2) library(dplyr) library(plotly) library(viridis) library(hrbrthemes) library(gapminder) # 前端UI ui <- fluidPage( titlePanel("2007年全球各国发展指标气泡图"), plotlyOutput("bubble_chart", height = "600px") ) # 后端服务逻辑 server <- function(input, output) { output$bubble_chart <- renderPlotly({ data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year) p <- data %>% mutate(gdpPercap=round(gdpPercap,0)) %>% mutate(pop=round(pop/1000000,2)) %>% mutate(lifeExp=round(lifeExp,1)) %>% arrange(desc(pop)) %>% mutate(country = factor(country, country)) %>% mutate(text = paste("国家: ", country, "\n人口(百万): ", pop, "\n预期寿命: ", lifeExp, "\n人均GDP: ", gdpPercap, sep="")) %>% ggplot( aes(x=gdpPercap, y=lifeExp, size = pop, color = continent, text=text)) + geom_point(alpha=0.7) + scale_size(range = c(1.4, 19), name="人口(百万)") + scale_color_viridis(discrete=TRUE, guide=FALSE) + theme_ipsum() + theme(legend.position="none") return(ggplotly(p, tooltip="text")) }) } # 启动Shiny应用 shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者piper180
相关产品推荐
相关产品推荐

