使用ggplot对散点图中的散点进行双重注释

时间:2019-03-24 20:39:30

标签: r ggplot2 shiny plotly scatter

我设计了一个闪亮的应用程序来绘制两个绘图。

其中一张图是散点图,通过更改颜色和大小可以突出显示选定的点。我的代码在这里:

output$ID <- renderPlotly({ # This render command makes everything inside the {} reactive (will update with changes to user input via widgets)

# Select the data for the chosen compartment using a switch statement.
# For a given input in the drop-down menu, it assigns the appropriate data frame to df to be plotted.
subject_id <- switch(input$ID,"1"=1,"2"=2,"3"=3,"4"=4,"5"=5)


g <- ggplot(Kcl_V %>% slice(-subject_id), aes(x = Vd, y = Cl)) + # Initialize ggplot object
  geom_point(colour = "#F8766D",size = 3)+
  geom_point(data = Kcl_V[subject_id, ],aes(x = Vd, y= Cl), colour = "#00BFC4", size = 4)
p <- ggplotly(g) # Convert to a plotly object.
# Doesn't create legend, but when hover over, does give label (which has to be the column name).

}) 信息已正确绘制,但是所选点始终具有双重注释,如下所示: enter image description here

有人知道如何避免这种情况吗?谢谢!

1 个答案:

答案 0 :(得分:1)

之所以会发生这种情况,是因为您在aes和第二次调用ggplot()中都设置了geom_point(),所以对于第二次geom_point中的所有数据,您有两组美观映射,从而产生2套工具提示。

有两种方法可以解决此问题。首先,您可以删除在aes中设置的ggplot,而分别在每个geom_point中对其进行设置,一个数据集和美学映射用于选定点,一个用于非选定点。 / p>

output$ID <- renderPlotly({ # This render command makes everything inside the {} reactive (will update with changes to user input via widgets)

  # Select the data for the chosen compartment using a switch statement.
  # For a given input in the drop-down menu, it assigns the appropriate data frame to df to be plotted.
  subject_id <- switch(input$ID,"1"=1,"2"=2,"3"=3,"4"=4,"5"=5)

  g <- ggplot() + # Initialize ggplot object
    geom_point(data = Kcl_V[-subject_id, ],aes(x = Vd, y= Cl),colour = "#F8766D",size = 3)+
    geom_point(data = Kcl_V[subject_id, ],aes(x = Vd, y= Cl), colour = "#00BFC4", size = 4)
  p <- ggplotly(g) # Convert to a plotly object.
  # Doesn't create legend, but when hover over, does give label (which has to be the column name).
})

或者,您可以在Kcl_V中创建一个布尔变量,以指示该行是否属于所选点,并使用此变量设置颜色和大小的美观映射。

output$ID <- renderPlotly({ # This render command makes everything inside the {} reactive (will update with changes to user input via widgets)

  # Select the data for the chosen compartment using a switch statement.
  # For a given input in the drop-down menu, it assigns the appropriate data frame to df to be plotted.
  selected_id <- switch(input$ID,"1"=1,"2"=2,"3"=3,"4"=4,"5"=5)

  g <- ggplot(Kcl_V %>% dplyr::mutate(selected = subject_id == selected_id),aes(x = Vd, y= Cl,color = selected, size = selected)) + # Initialize ggplot object
    scale_color_manual(values = c("TRUE"="#00BFC4","FALSE"="#F8766D")) +
    scale_size_manual(values = c("TRUE"=4,"FALSE"=3))
  p <- ggplotly(g) # Convert to a plotly object.
  # Doesn't create legend, but when hover over, does give label (which has to be the column name).
})