I am working on a chart in ggplot. Some of my numbers are large (1000+) so I want to use commas as a thousands separator to make numbers easier to read. The problem is that I can’t figure out how to do that without R adding extra space to the left of the number in the data label box. Below is the code I tried, and the picture to demonstrate the problem. Any solutions? Thanks in advance!
df <- data.frame( Year = c(2020, 2021, 2022, 2023),
Var1 = c(1509.89, 21698, 140.98, 500),
Var2 = c(2, 3000.9, 410.4, 5),
Var3 = c(198.51, 2430.49, 421, 4853) )
spline_Var1 <- as.data.frame(spline(df$Year, df$Var1))
spline_Var2 <- as.data.frame(spline(df$Year, df$Var2))
spline_Var3 <- as.data.frame(spline(df$Year, df$Var3))
splines <- bind_rows(
list(Var1 = spline_Var1,
Var2 = spline_Var2,
Var3 = spline_Var3),
.id = "var"
)
df <- df |>
pivot_longer(
cols = c(Var1, Var2, Var3), names_to = "var", values_to = "value"
)
ggplot(df) +
geom_point(aes(x = Year, y = value, colour = var)) +
geom_line(aes(x = x, y = y, colour = var), data = splines) +
geom_label_repel(aes(x = Year, y = value,
label = format(round(value, digits = 0),big.mark=",",scientific=FALSE)),
max.overlaps = Inf)
New contributor
Amanda Lemon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.