Home > OS >  ggspatial::geom_spatial_path() function not working as intended
ggspatial::geom_spatial_path() function not working as intended

Time:11-06

I'm currently studying the basics of GIS with R at this enter image description here

But when I use ggplot2 and ggspatial packages, a 4th line is added to speed_limit plot, and I really don't know why.

sp_df <- ggspatial::df_spatial(line_sf)

p1 <- ggplot2::ggplot(sp_df, aes(x,y))  
  ggspatial::geom_spatial_path(aes(colour = road_name))  
  ggspatial::coord_sf(crs = 4326)  
  xlab("lon")  
  ylab("lat")  
  ggtitle("road_name")


p2 <- ggplot2::ggplot(sp_df, aes(x,y))  
  ggspatial::geom_spatial_path(aes(color = speed_limit))  
  ggspatial::coord_sf(crs = 4326)  
  xlab("lon")  
  ylab("lat")  
  ggtitle("speed_limit")

p1 / p2

enter image description here

What's the problem here? Where that additional line comes from? Am I doing something wrong or is this a bug? Any help is appreciated.

CodePudding user response:

You seem to be doing things the hard way, since ggplot has excellent sf support. Rather than loading an extra dependency, using extra code and converting to a data frame, why not simply plot the sf object directly?

p1 <- ggplot(line_sf)  
  geom_sf(aes(geometry = line_sfc, color = road_name))  
  labs(title = "road_name", x = "lon", y = "lat") 

p2 <- ggplot(line_sf)  
  geom_sf(aes(geometry = line_sfc, color = speed_limit))  
  labs(title = "speed_limit", x = "lon", y = "lat")

p1 / p2

enter image description here

If you have good reasons for converting to a data frame, the alternative is to group the second plot by road name so that adjacent groups aren't connected:

sp_df <- ggspatial::df_spatial(line_sf)

p1 <- ggplot2::ggplot(sp_df, aes(x,y))  
  ggspatial::geom_spatial_path(aes(colour = road_name))  
  ggspatial::coord_sf(crs = 4326)  
  xlab("lon")  
  ylab("lat")  
  ggtitle("road_name")

ggplot2::ggplot(sp_df, aes(x,y))  
  ggspatial::geom_spatial_path(aes(color = speed_limit, group = road_name))  
  ggspatial::coord_sf(crs = 4326)  
  xlab("lon")  
  ylab("lat")  
  ggtitle("speed_limit")

p1 / p2

enter image description here

  • Related