【问题标题】:ggplot combine geom_text_repel with facet_zoomggplot 结合 geom_text_repel 和 facet_zoom
【发布时间】:2023-04-06 14:24:02
【问题描述】:

我有以下代码示例:

x <- c(1,1.2,1.3,1.1,2,2.5,3.6)
y <- c(3,3.1,2.9,3.6,4.5,5.6,6.7)
z <- c('Austria',' Germany', 'Italy', 'France', 'Spain','Portugal', 'Belgium')

dataset <-data.frame(x,y,z)

ggp <- ggplot(dataset, mapping = aes(x=x, y=y)) +
 
   geom_text_repel(mapping = aes(label = z),
              size = 2,
              min.segment.length = 0,
              seed = 42,
              box.padding = 0.4,
              arrow = arrow(length = unit(0.007, "npc")),
              nudge_x = .03,
              nudge_y = .03,
              color = "grey60") +

  geom_point(data = dataset,aes(colour=z, size = y/x), alpha=0.6) +

  facet_zoom(x = x < 2, horizontal = FALSE ,zoom.size = 0.3, show.area = FALSE) + 
  coord_cartesian(clip="off")

 ggp

我只想在主面板上显示不在分面缩放中的点的名称,而在分面缩放中我只想显示可见点的名称。有没有办法同时做到这两点?

我也想避免使用 geom_text

【问题讨论】:

    标签: r ggplot2 facet geom-text geom-point


    【解决方案1】:

    我认为你可以使用来自facet_zoomzoom.data 参数:

    zoom.data:计算为逻辑向量的表达式。如果为真 数据仅显示在缩放面板中。如果为 FALSE,则数据仅显示在 上下文面板。如果 NA 数据将显示在所有面板中。

    首先,将zoom 列添加到您的数据集,如果x 小于2,则设置为TRUE(这将显示在缩放面板中)。否则,zoom 应设置为 FALSE(这将显示在上下文面板中)。

    dataset$zoom <- ifelse(dataset$x < 2, TRUE, FALSE)
    

    对于facet_zoom,使用zoom.data 参数并设置为新的zoom 列:

    facet_zoom(x = x < 2, horizontal = FALSE, zoom.data = zoom, zoom.size = 0.3, show.area = FALSE)
    

    这里是重现性的完整代码:

    library(ggplot2)
    library(ggrepel)
    library(ggforce)
    
    x <- c(1,1.2,1.3,1.1,2,2.5,3.6)
    y <- c(3,3.1,2.9,3.6,4.5,5.6,6.7)
    z <- c('Austria',' Germany', 'Italy', 'France', 'Spain','Portugal', 'Belgium')
    
    dataset <-data.frame(x,y,z)
    
    dataset$zoom <- ifelse(dataset$x < 2, TRUE, FALSE)
    
    ggp <- ggplot(dataset, mapping = aes(x=x, y=y)) +
      
      geom_text_repel(mapping = aes(label = z),
                      size = 2,
                      min.segment.length = 0,
                      seed = 42,
                      box.padding = 0.4,
                      arrow = arrow(length = unit(0.007, "npc")),
                      nudge_x = .03,
                      nudge_y = .03,
                      color = "grey60") +
      
      geom_point(aes(colour=z, size = y/x), alpha=0.6) +
      
      facet_zoom(x = x < 2, horizontal = FALSE , zoom.data = zoom, zoom.size = 0.3, show.area = FALSE) + 
      coord_cartesian(clip="off")
    
    ggp
    

    情节

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2017-05-22
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多