Adding convex hull to ggplot map

后端 未结 1 1267
栀梦
栀梦 2021-02-20 03:19

I am trying to create a ggplot that includes coordinates, density, and a convex hull polygon.

The data is a set of twenty latitudinal and longitudinal points.

1条回答
  •  -上瘾入骨i
    2021-02-20 03:32

    Your problem is with the ddply: currently your code splits the data by distinct values of Latitude and Longitude (i.e. each point you're plotting), finds the convex hull in each split (which is just the point itself) and binds the results together, effectively just giving you a row for each point in your data. That's why the polygon you draw touches every point.

    Here's a solution that should work:

    library(tidyverse)
    
    # Find the convex hull of the points being plotted
    hull <- mtcars %>%
      slice(chull(mpg, wt))
    
    # Define the scatterplot
    p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(shape = 21)
    
    # Overlay the convex hull
    p + geom_polygon(data = hull, alpha = 0.5)
    

    Now if you wanted to add a grouping to your plot, all you need to do is calculate the chull for each level of your grouping variable:

    # Calculate the hulls for each group
    hull_cyl <- mtcars %>%
      group_by(cyl) %>%
      slice(chull(mpg, wt))
    
    # Update the plot with a fill group, and overlay the new hulls
    p + aes(fill = factor(cyl)) + geom_polygon(data = hull_cyl, alpha = 0.5)
    

    Created on 2018-02-12 by the reprex package (v0.2.0).

    By the way, there's also a nice example in one of the ggplot2 vignettes, where they go through a step-by-step guide to creating custom stats and geoms, using the convex hull as an example: https://cran.r-project.org/web/packages/ggplot2/vignettes/extending-ggplot2.html.

    0 讨论(0)
提交回复
热议问题