我一直在查看许多资源,很难找到具有交互式绘图所有功能的可重现示例。我真的希望一个闪亮的应用程序中的情节具有这些功能,这些功能类似于提供的选项plotly()
:
- 当一个区域被刷并双击时有一个缩放选项
- 可以选择删除与其图例对应的点
- 悬停在顶部时显示点的 x 和 y 值
我无法在同一代码中找到所有这些功能。我个人希望每个散点图都应该具有这些功能,如果它们用于闪亮的应用程序。由于这个功能在ggplot()
很多人中偏爱plotly()
。在看到这个问题的答案后,我希望每个人都更喜欢使用ggplot()
alonf withshiny
我创建了缩放功能,帮助我使用第二个和第三个功能,即当在图例中单击第 1 组时删除与第 1 组对应的点的选项,并在鼠标悬停在其上方时显示点的 x 和 y 轴值。谢谢!!!
以下是开始使用的示例数据和代码。
library(ggplot2)
library(ggrepel)
library(shiny)
ui=fluidPage(uiOutput("plot"))
server = function(input, output) {
#creating a range variable for zooming
ranges <<- reactiveValues(x = NULL, y = NULL)
#Creating sample Data
Data=data.frame(Group=c("Group 2","Group 1","Group 3","Group 2","Group 5","Group 4","Group 6",
"Group 7","Group 4","Group 3","Group 1","Group 5","Group 6","Group 7",
"Group 2","Group 4","Group 6","Group 7","Group 3","Group 1"),
Fruit=c("apple","apple","apple","mango","apple","apple","apple","apple","mango","mango",
"mango","mango","mango","mango","orange","orange","orange","orange","orange",
"orange"),
Percentage=c(68.46846847,77.35849057,72.72727273,26.12612613,76.31578947,62.79069767,
71.05263158,69.23076923,30.23255814,25,20.75471698,23.68421053,23.68421053,
23.07692308,5.405405405,6.976744186,5.263157895,7.692307692,2.272727273,
1.886792453))
#Creating the plor function
output$graph<-renderPlot({
ggplot(Data,aes(y=reorder(Fruit,Percentage),x=Percentage,
color=Group,
label=paste0(round(Percentage),"%")))+
geom_point(size=4)+
scale_x_continuous(limits=c(0,100))+
theme(panel.grid.major.y=element_line(color="gray90",size = 0.7),
panel.background=element_blank(),
strip.background=element_blank(),
panel.border=element_rect(color="black",fill=NA,size=1))+
labs(y="",x="% of people",color="")+
# geom_text_repel(direction="y",nudge_y = 0.2, point.padding = 0.1, box.padding = 0.1)+
coord_cartesian(xlim = ranges$x, ylim = ranges$y, expand = T)
})
#Rendering the plot with the brush parameter
output$plot=renderUI(
plotOutput("graph",dblclick = "plot1_dblclick",brush = brushOpts(id = "plot1_brush",resetOnNew = TRUE),height=450,width=900)
)
#To observe and change the limits of the graph (zooming)
observeEvent(input$plot1_dblclick, {
brush <- input$plot1_brush
if (!is.null(brush)) {
ranges$x <- c(brush$xmin, brush$xmax)
ranges$y <- c(brush$ymin, brush$ymax)
} else {
ranges$x <- NULL
ranges$y <- NULL
}
})
}
shinyApp(ui=ui,server=server)