I am creating a map and then adding some cities on top of it, and I want to have multiple legend items.
So far I have this code:
library(tidyverse)
library(raster)
library(sf)
library(maptools)
#a location to add to the map
city <- tibble(y = c(47.7128),
x = c(74.0060))
city <- st_as_sf(city, coords = c("x", "y"), crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
#world map to plot, along with a raster of distance from a point
data(wrld_simpl)
wrld_simpl_sf <- sf::st_as_sf(wrld_simpl)
r <- raster(wrld_simpl, res = 1)
wrld_r <- rasterize(wrld_simpl, r)
#
pt1 <- matrix(c(100,0), ncol = 2)
dist1 <- distanceFromPoints(r, pt1)
values(dist1)[values(dist1) > 5e6] <- NA
plot(dist1)
gplot_data <- function(x, maxpixels = 50000) {
x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE)
coords <- raster::xyFromCell(x, seq_len(raster::ncell(x)))
## Extract values
dat <- utils::stack(as.data.frame(raster::getValues(x)))
names(dat) <- c('value', 'variable')
dat <- dplyr::as.tbl(data.frame(coords, dat))
if (!is.null(levels(x))) {
dat <- dplyr::left_join(dat, levels(x)[[1]],
by = c("value" = "ID"))
}
dat
}
gplot_dist1 <- gplot_data(dist1)
gplot_wrld_r <- gplot_data(wrld_r)
#plot data
ggplot() +
geom_sf(data = wrld_simpl_sf, fill = "grey20",
colour = "white", size = 0.2) +
geom_tile(data = gplot_dist1,
aes(x = x, y = y, fill = value)) +
scale_fill_gradient("Distance",
low = 'yellow', high = 'blue',
na.value = NA) +
geom_sf(data = city, fill = "red", color = "red", size = 3, shape = 21)
which returns:
This is all fine but now I just want to add the red point from geom_sf(data = city, fill = "red", color = "red", size = 3, shape = 21) to the legend with the caption "Cities".
You could use the scale_color_manual function. The way I understand (I found out about this today), it allows you to map colors to "levels" that then appear in the legend.
Changing your code to have the following does the trick.
geom_sf(data = city, fill = "red", aes(color = "Cities"), size = 3, shape = 21) +
scale_color_manual(values = c("Cities" = "red"))
This is the result
Related
I would like to ask is there a way how to set xend and yend from geom_segment arguments in leaflet`s addPolylines function?
insted of explaining I rather provide reproduceble example since it is mut easire to see rather than explain:
library(leaflet)
library(spdep)
library(ggplot2)
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_DEU_1_sp.rds"
data <- readRDS(url(URL))
cns <- knearneigh(coordinates(data), k = 1, longlat = T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cns
scnsn
cS <- nb2listw(scnsn)
# Plotting results
plot(data)
plot(cS, coordinates(data), add = T)
# Plotting in ggplot
# Converting to data.frame
data_df <- data.frame(coordinates(data))
colnames(data_df) <- c("long", "lat")
n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
from = rep(1:n,sapply(cS$neighbours,length)),
to = unlist(cS$neighbours),
weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")
ggplot(data, aes(x = long, y =lat))+
geom_polygon(aes(group = group), color = "black", fill = FALSE)+
geom_point(data = data_df, aes(x= long, y = lat), size = 1)+
geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "red")
# Plotting in leaflet
leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=data, weight = 0.8, fill = F, color = "red") %>%
addPolylines(data=DA, lng = DA$long_to, lat = DA$lat_to, weight = 0.85)
It can be seen then result in leaflet are not right (Spatial Map is different) how ever plots in basic plot and ggplot are how things should look like,
Is there a way how to reproduce plots above in leaflet? Reading leaflet documentation did not help me
A possible workaround is to use the function addFlows() implemented in library(leaflet.minicharts).
leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=data, weight = 0.8, fill = F, color = "red") %>%
addFlows(lng0 = DA$long, lat0 = DA$lat,lng1 = DA$long_to, lat1 = DA$lat_to, dir = 1, maxThickness= 0.85)
I would like to have only one half of violin plots (similar to the plots created by stat_density_ridges from ggridges). A MWE
library(ggplot2)
dframe = data.frame(val = c(), group = c())
for(i in 1:5){
offset = i - 3
dframe = rbind(dframe,
data.frame(val = rnorm(n = 50, mean = 0 - offset), group = i)
)
}
dframe$group = as.factor(dframe$group)
ggplot(data = dframe, aes(x = group, y = val)) +
geom_violin()
produces a plot like this
I though would like to have one looking like this:
Ideally, the plots would also be scaled to like 1.5 to 2 times the width.
There's a neat solution by #David Robinson (original code is from his gists and I did only a couple of modifications).
He creates new layer (GeomFlatViolin) which is based on changing width of the violin plot:
data <- transform(data,
xmaxv = x,
xminv = x + violinwidth * (xmin - x))
This layer also has width argument.
Example:
# Using OPs data
# Get wanted width with: geom_flat_violin(width = 1.5)
ggplot(dframe, aes(group, val)) +
geom_flat_violin()
Code:
library(ggplot2)
library(dplyr)
"%||%" <- function(a, b) {
if (!is.null(a)) a else b
}
geom_flat_violin <- function(mapping = NULL, data = NULL, stat = "ydensity",
position = "dodge", trim = TRUE, scale = "area",
show.legend = NA, inherit.aes = TRUE, ...) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomFlatViolin,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
trim = trim,
scale = scale,
...
)
)
}
GeomFlatViolin <-
ggproto("GeomFlatViolin", Geom,
setup_data = function(data, params) {
data$width <- data$width %||%
params$width %||% (resolution(data$x, FALSE) * 0.9)
# ymin, ymax, xmin, and xmax define the bounding rectangle for each group
data %>%
group_by(group) %>%
mutate(ymin = min(y),
ymax = max(y),
xmin = x - width / 2,
xmax = x)
},
draw_group = function(data, panel_scales, coord) {
# Find the points for the line to go all the way around
data <- transform(data,
xmaxv = x,
xminv = x + violinwidth * (xmin - x))
# Make sure it's sorted properly to draw the outline
newdata <- rbind(plyr::arrange(transform(data, x = xminv), y),
plyr::arrange(transform(data, x = xmaxv), -y))
# Close the polygon: set first and last point the same
# Needed for coord_polar and such
newdata <- rbind(newdata, newdata[1,])
ggplot2:::ggname("geom_flat_violin", GeomPolygon$draw_panel(newdata, panel_scales, coord))
},
draw_key = draw_key_polygon,
default_aes = aes(weight = 1, colour = "grey20", fill = "white", size = 0.5,
alpha = NA, linetype = "solid"),
required_aes = c("x", "y")
)
Package see has also a function geom_violinhalf that seems to do exactly what you want (see right plot below). It behaves mostly like geom_violin(), except that it does not have all arguments geom_violin() has (missing for example draw_quantiles)
library(ggplot2)
library(see)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p1 <- p + geom_violin()+ ggtitle("geom_violin")
p2 <- p + see::geom_violinhalf()+ ggtitle("see::geom_violinhalf")
## show them next to each other
library(patchwork)
p1+p2
Created on 2020-04-30 by the reprex package (v0.3.0)
Very much related to this question I am trying to plot some world regions, now using a Mercator projection, but keep getting into trouble when adding x and y limits:
ggplot(world, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "black", colour = "black") +
coord_map(projection = "mercator", xlim = c(-125, -30), ylim = c(-60, 35))
Obviously not great. When I use coord_cartesian (as suggested here) to set the limits, I loose the Mercator projection:
ggplot(world, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "black", colour = "black") +
coord_map(projection = "mercator") +
coord_cartesian(xlim = c(-125, -30), ylim = c(-60, 35))
When I use lims I get what I want for Latin America:
ggplot(world, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "black", colour = "black") +
coord_map(projection = "mercator") +
lims(x = c(-125, -30), y = c(-60, 35))
Problem is, this approach does not always work, for example for Africa or Asia I start to get some crazy behaviour towards the plot border:
ggplot(world, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "black", colour = "black") +
coord_map(projection = "mercator") +
lims(x = c(-20, 45), y = c(-50, 40))
# lims(x = c(40, 150), y = c(-10, 55))
A solution here could be to convert the lat/lon coordinates to "proper" web mercator coordinates (here I'm using epsg 3857, which is the "google" projection), and then plotting using those "new" coordinates.
Assuming that original coordinates are latlon wgs84 (epsg 4326), this can be achieved like this:
worldmerc <- SpatialPointsDataFrame(coords = data_frame(x = world$long, y = world$lat),
data = world, proj4string = CRS("+proj=longlat +datum=WGS84")) %>%
subset((lat < 90 & lat > -90)) %>% # needed because transform not defined at the poles !!!!
spTransform(CRS("+init=epsg:3857"))
worldmerc <- mutate(worldmerc#data, longmerc = coordinates(worldmerc)[,1], latmerc = coordinates(worldmerc)[,2])
Plotting the whole data gives you this (Note the use of coord_fixed to preserve aspect ratio !:
ggplot(worldmerc, mapping = aes(x = longmerc, y = latmerc, group = group)) +
geom_polygon(fill = "black", colour = "black") +coord_fixed()
Now, the problem is that to do subsetting you would now need to enter "map" coordinates instead than lat long, but also that can be tweaked:
#For South America
xlim = c(-125, -30)
ylim = c(-60, 35)
lims = SpatialPoints(coords = data_frame(x = xlim, y = ylim), proj4string = CRS("+proj=longlat +datum=WGS84"))%>%
spTransform(CRS("+init=epsg:3857"))
ggplot(worldmerc, mapping = aes(x = longmerc, y = latmerc, group = group)) +
geom_polygon(fill = "black", colour = "black")+
coord_fixed(xlim = coordinates(lims)[,1], ylim = coordinates(lims)[,2])
#for africa
xlim = c(-20,45)
ylim = c(-50,40)
lims = SpatialPoints(coords = data_frame(x = xlim, y = ylim), proj4string = CRS("+proj=longlat +datum=WGS84"))%>%
spTransform(CRS("+init=epsg:3857"))
ggplot(worldmerc, mapping = aes(x = longmerc, y = latmerc, group = group)) +
geom_polygon(fill = "black", colour = "black")+
coord_fixed(xlim = coordinates(lims)[,1], ylim = coordinates(lims)[,2])
As you can see, in both cases you get "correct" maps.
Now, last thing you may want to do is maybe have "lat/lon" coordinates on the axis. That's a bit of a hack but can be done like this:
library(magrittr)
xlim = c(-125, -30)
ylim = c(-60, 35)
# Get the coordinates of the limits in mercator projection
lims = SpatialPoints(coords = data_frame(x = xlim, y = ylim),
proj4string = CRS("+proj=longlat +datum=WGS84"))%>%
spTransform(CRS("+init=epsg:3857"))
# Create regular "grids" of latlon coordinates and find points
# within xlim/ylim - will be our labels
majgrid_wid_lat = 20
majgrid_wid_lon = 30
majbreaks_lon = data_frame(x=seq(-180, 180, majgrid_wid_lon)) %>%
filter(x >= xlim[1] & x <= xlim[2]) %>%
as.data.frame()
majbreaks_lat = data_frame(x=seq(-90, 90, majgrid_wid_lat)) %>%
filter(x >= ylim[1] & x <= ylim[2]) %>%
as.data.frame()
#Find corresponding mercator coordinates
mercbreaks_lat = SpatialPoints(coords = expand.grid(x = majbreaks_lon$x, y = majbreaks_lat$x), proj4string = CRS("+init=epsg:4326"))%>%
spTransform(CRS("+init=epsg:3857")) %>% coordinates() %>% extract(,2) %>% unique()
mercbreaks_lon = SpatialPoints(coords = expand.grid(x = majbreaks_lon$x, y = majbreaks_lat$x), proj4string = CRS("+init=epsg:4326"))%>%
spTransform(CRS("+init=epsg:3857")) %>% coordinates() %>% extract(,1) %>% unique()
# Plot using mercator coordinates, but latlon labels
ggplot(worldmerc, mapping = aes(x = longmerc, y = latmerc, group = group)) +
geom_polygon(fill = "black", colour = "black") +
coord_fixed(xlim = coordinates(lims)[,1], ylim = coordinates(lims)[,2])+
scale_x_continuous("lon", breaks = mercbreaks_lon, labels = signif(majbreaks_lon$x, 2)) +
scale_y_continuous("lat", breaks = mercbreaks_lat, labels = signif(majbreaks_lat$x,2))+theme_bw()
, which gives:
It's a bit convoluted and there could be better ways, but it does the trick, and could be easily transformed in a function.
HTH,
Lorenzo
I have the following r code using the Google Map library
library(ggmap)
map <- get_map(location = 'Asia', zoom = 4)
mapPoints <- ggmap(map)
I had to plot two points
mapPoints +
geom_point(aes(x = lon, y = lat, col = "orange"), data = airportD)
Now I want to draw a line between these points, how can I obtain this result?
It shouldn't be any different than adding a layer to any other ggplot object.
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = TRUE)
names(airports) <- c("id", "name", "city", "country", "code",
"icao", "lat", "lon", "altitude", "timezone", "dst", "tz")
airportD <- airports[airports$city %in% c("Beijing", "Bangkok", "Shanghai"), ]
map <- get_map(location = 'Asia', zoom = 4)
mapPoints <- ggmap(map)
mapPoints +
geom_point(aes(x = lon, y = lat), col = "orange", data = airportD)
mapPoints +
geom_line(aes(x = lon, y = lat), col = "orange", data = airportD)
I've been reading the vignette on extending ggplot2, but I'm a bit stuck on how I can make a single geom that can add multiple geometries to the plot. Multiple geometries already exist in ggplot2 geoms, for example, we have things like geom_contour (multiple paths), and geom_boxplot (multiple paths and points). But I can't quite see how to extend those into new geoms.
Let's say I'm trying to make a geom_manythings that will draw two polygons and one point by computing on a single dataset. One polygon will be a convex hull for all the points, the second polygon will be a convex hull for a subset of the points, and the single point will represent the centre of the data. I want all of these to appear with a call to one geom, rather than three separate calls, as we see here:
# example data set
set.seed(9)
n <- 1000
x <- data.frame(x = rnorm(n),
y = rnorm(n))
# computations for the geometries
# chull for all the points
hull <- x[chull(x),]
# chull for all a subset of the points
subset_of_x <- x[x$x > 0 & x$y > 0 , ]
hull_of_subset <- subset_of_x[chull(subset_of_x), ]
# a point in the centre of the data
centre_point <- data.frame(x = mean(x$x), y = mean(x$y))
# plot
library(ggplot2)
ggplot(x, aes(x, y)) +
geom_point() +
geom_polygon(data = x[chull(x),], alpha = 0.1) +
geom_polygon(data = hull_of_subset, alpha = 0.3) +
geom_point(data = centre_point, colour = "green", size = 3)
I want to have a geom_manythings to replace the three geom_* in the code above.
In an attempt to make a custom geom, I started with code in geom_tufteboxplot and geom_boxplot as templates, along with the 'extending ggplot2' vignette:
library(ggplot2)
library(proto)
GeomManythings <- ggproto(
"GeomManythings",
GeomPolygon,
setup_data = function(self, data, params) {
data <- ggproto_parent(GeomPolygon, self)$setup_data(data, params)
data
},
draw_group = function(data, panel_scales, coord) {
n <- nrow(data)
if (n <= 2)
return(grid::nullGrob())
common <- data.frame(
colour = data$colour,
size = data$size,
linetype = data$linetype,
fill = alpha(data$fill, data$alpha),
group = data$group,
stringsAsFactors = FALSE
)
# custom bits...
# polygon hull for all points
hull <- data[chull(data), ]
hull_df <- data.frame(x = hull$x,
y = hull$y,
common,
stringsAsFactors = FALSE)
hull_grob <-
GeomPolygon$draw_panel(hull_df, panel_scales, coord)
# polygon hull for subset
subset_of_x <-
data[data$x > 0 & data$y > 0 ,]
hull_of_subset <-
subset_of_x[chull(subset_of_x),]
hull_of_subset_df <- data.frame(x = hull_of_subset$x,
y = hull_of_subset$y,
common,
stringsAsFactors = FALSE)
hull_of_subset_grob <-
GeomPolygon$draw_panel(hull_of_subset_df, panel_scales, coord)
# point for centre point
centre_point <-
data.frame(x = mean(coords$x),
y = coords(data$y),
common,
stringsAsFactors = FALSE)
centre_point_grob <-
GeomPoint$draw_panel(centre_point, panel_scales, coord)
# end of custom bits
ggname("geom_mypolygon",
grobTree(hull_grob,
hull_of_subset_grob,
centre_point_grob))
},
required_aes = c("x", "y"),
draw_key = draw_key_polygon,
default_aes = aes(
colour = "grey20",
fill = "grey20",
size = 0.5,
linetype = 1,
alpha = 1,
)
)
geom_manythings <-
function(mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
...) {
layer(
geom = GeomManythings,
mapping = mapping,
data = data,
stat = stat,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
But clearly there are quite a few things not right in this geom, I must be missing some fundamental details...
ggplot(x, aes(x, y)) +
geom_point() +
geom_manythings()
How can I write this geom to get the desired result?
there are quite a few issues in your code, so I suggest you try with a simplified case first. In particular, the chull calculation was problematic. Try this,
library(ggplot2)
library(proto)
library(grid)
GeomManythings <- ggproto(
"GeomManythings",
Geom,
setup_data = function(self, data, params) {
data <- ggproto_parent(Geom, self)$setup_data(data, params)
data
},
draw_group = function(data, panel_scales, coord) {
n <- nrow(data)
if (n <= 2)
return(grid::nullGrob())
# polygon hull for all points
hull_df <- data[chull(data[,c("x", "y")]), ]
hull_grob <-
GeomPolygon$draw_panel(hull_df, panel_scales, coord)
# polygon hull for subset
subset_of_x <-
data[data$x > 0 & data$y > 0 ,]
hull_of_subset_df <-subset_of_x[chull(subset_of_x[,c("x", "y")]),]
hull_of_subset_df$fill <- "red" # testing
hull_of_subset_grob <- GeomPolygon$draw_panel(hull_of_subset_df, panel_scales, coord)
coords <- coord$transform(data, panel_scales)
pg <- pointsGrob(x=mean(coords$x), y=mean(coords$y),
default.units = "npc", gp=gpar(col="green", cex=3))
ggplot2:::ggname("geom_mypolygon",
grobTree(hull_grob,
hull_of_subset_grob, pg))
},
required_aes = c("x", "y"),
draw_key = draw_key_polygon,
default_aes = aes(
colour = "grey20",
fill = "grey50",
size = 0.5,
linetype = 1,
alpha = 0.5
)
)
geom_manythings <-
function(mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
...) {
layer(
geom = GeomManythings,
mapping = mapping,
data = data,
stat = stat,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
set.seed(9)
n <- 20
d <- data.frame(x = rnorm(n),
y = rnorm(n))
ggplot(d, aes(x, y)) +
geom_manythings()+
geom_point()
(disclaimer: I haven't tried to write a geom in 5 years, so I don't know how it works nowadays)