This question uses the public data and code from another question
I am trying to add labels to my map. When I use geom_text, each label correctly appears once but collided (right side). To avoid collision, I am using geom_text_repel (The stick and text make it look cleaner) but when I use it the labels appear multiple times (left side) as you can see in my picture. Does anyone know what may be the issue? I tried a inner join instead of a left join but that did not work so I tried manipulating the options in geom_text_repel with no success. Thanks in advance for any assistance you can provide.
I checked here and here for assistance but still the issue occurs.
library(ggplot2)
library(sf)
library(tidyverse)
library(ggrepel)
map7 <- read_sf("england_ct_1991.shp")
totalPrices <- read_csv("england_ct_1991.csv")
new <- totalPrices %>%
group_by(name) %>%
mutate(price = rnorm(1)) %>%
distinct(name, price)
new
map7 %>%
left_join(new) %>%
ggplot() +
geom_sf(aes(fill = price),color="black")
cnames <- aggregate(cbind(x, y, price) ~ name, data=totalPrices,
FUN=function(x)mean(range(x)))
head(cnames)
# cnames code is from [here][4]
map7 %>%
left_join(cnames) %>%
ggplot() +
geom_sf(aes(fill = price),color="black")+
theme(axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.y=element_blank(),
axis.title.x=element_blank(),
rect = element_blank(),
panel.background = element_blank()) +
scale_fill_gradient(low = "white", high = "black", na.value = "red",
guide = 'colorbar', aesthetics = 'fill') +
#geom_text( aes(x, y, label = name)) +
geom_text_repel( aes(x, y, label = name, geometry = geometry), stat = "sf_coordinates",
show.legend=FALSE, size = 3)
Because there are multiple sets of geometry within the same name. One fix of this is to keep one name only for those multiple sets of geometry. A quick solution is to keep the first name and replace the rest with NA or " ".
map7 %>%
left_join(cnames) %>%
mutate(name_1 = ifelse(row_number() == 1, name, NA), .by = name) %>%
ggplot() +
geom_sf(aes(fill = price), color = "black") +
theme(
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
rect = element_blank(),
panel.background = element_blank()
) +
scale_fill_gradient(
low = "white", high = "black", na.value = "red",
guide = "colorbar", aesthetics = "fill"
) +
geom_text_repel(aes(x, y, label = name_1, geometry = geometry),
stat = "sf_coordinates",
show.legend = FALSE, size = 3
)
Alternatively, we could manually choose which name to use.