【问题标题】:How to cluster points around a center in ggplot如何在ggplot中围绕中心聚集点
【发布时间】:2021-07-13 00:41:26
【问题描述】:

我有一个数据框,其中包含少量坐标位置,但每个位置都有多个观察值。我想绘制每个观察值,但由于坐标相同,它们重叠。下面提供了示例数据

library(ggplot2)
data <- data.frame(lon = c(rep(-100, 15), rep(-98, 10), rep(-96, 8)),
                   lat = c(rep(50, 15), rep(58, 10), rep(46, 8)),
                   n = runif(33, 0, 300))
ggplot(data=data, aes(x=lon, y=lat, color=n)) + 
  geom_point()

我希望所有点都聚集在提供的经纬度坐标周围,而不是让这些点重叠。我尝试过使用抖动,但是点太分散了。我正在寻找它们在(有点)圆形集群中。我该怎么办?

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    几个选项:

    1. 快速简单:使用position_jitterwidthheight 参数来控制点的分布,这将需要一些反复试验才能获得所需的外观。

    2. 从字面上修改点的纬度和经度以在实际经度和经度周围创建一个圆圈,这有点有趣。

    选项 1

    library(ggplot2)
    
    ggplot(data=data, aes(x=lon, y=lat, color=n)) + 
      geom_point(position = position_jitter(width = 0.15, height = 0.75, seed = 123))
    

    选项 2

    library(ggplot2)
    library(dplyr)
    
    # controls the spread of points
    radius <- 0.5
    
    data1 <- 
      data %>% 
      mutate(point = c(rep("a", 15), rep("b", 10), rep("c", 8))) %>% 
      group_by(point) %>% 
      mutate(point_id = row_number(),
             x_offset = sin(point_id*2*pi/max(point_id)) * radius,
             y_offset = cos(point_id*2*pi/max(point_id)) * radius,
             lon_mod = lon + x_offset,
             lat_mod = lat + y_offset)
             
    # need to keep the x and y axis to the same scale to avoid distortion of the  points
    # you could even apply a minimal jitter to these points if you felt it improves the appearance.
             
    ggplot(data1, aes(lon_mod, lat_mod, color=n)) + 
      geom_point()+
      coord_fixed()
    

    reprex package (v2.0.0) 于 2021-07-12 创建

    【讨论】:

      【解决方案2】:

      我们可以使用geom_jitter

      ggplot(data=data, aes(x=lon, y=lat, color=n))  +
          geom_jitter()
      

      要修改geom_jitter,请使用widthheight 来塑造您的集群:

      ggplot(data=data, aes(x=lon, y=lat, color=n))  +
          geom_jitter(width = 0.15, height = 0.35)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 2018-08-28
        • 2013-05-20
        • 2020-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多