I'm trying to use geom_text as the legend for my line graph, but I also need to have COUNT as labels (work requirement).
When I run the code below, I can get both labels, the values and the category names and format them differently so the legend is more obvious.
But if the final COUNT are the same, the order of the labels changes each time the code is run. So some times the correct COUNT lines up with the correct label for the legend, but run it again and the labels will have mixed up.
df <- data.frame(YEAR = c(2017,2018,2019,2017,2018,2019,2017,2018,2019),
SPLIT = c("Cat A","Cat A","Cat A","Cat B","Cat B","Cat B","Cat C","Cat C","Cat C"),
COUNT = c(11,12,15,6,8,12,15,14,12)
)
ggplot(df, aes(YEAR, COUNT, label = COUNT, colour = SPLIT, group = SPLIT)) +
geom_line(size = 1) +
scale_x_continuous(labels = as.character(df$YEAR), breaks =df$YEAR, limits = c(min(df$YEAR), max(df$YEAR+0.3)))+
geom_text_repel(data = subset(df, YEAR == max(YEAR)), aes(label = SPLIT), show.legend = FALSE, size = 4, fontface = "bold", hjust = "left",nudge_x = 0.2,direction = "y", segment.color = NA) +
geom_text_repel(data = subset(df, YEAR == max(YEAR)), aes(label = COUNT), show.legend = FALSE, size = 3,direction = "y", segment.color = NA) +
theme(legend.position="none")
I know that I can create an additional field using paste(Col1,Col2) and just use one geom_text, but then the labels are formatted the same and I wanted them to be different.
I've tried directlabels, but the labels were too close together. I reduced the font size but it was still too close together.
I suppose there are a few questions here:
Thanks for any help.
How about removing one of the geom_text_repels
and passing in SPLIT2
variable which utilizes the glue
package to concatenate SPLIT
and COUNT
.
Doing this changes the ordering of the labels for Cat C
and Cat B
.
I would also suggest you consider changing the nudge_x
from 0.2
to 0.05
.
library(tidyverse)
library(lubridate)
library(ggrepel)
library(glue)
df <- data.frame(YEAR = c(2017,2018,2019,2017,2018,2019,2017,2018,2019),
SPLIT = c("Cat A","Cat A","Cat A","Cat B","Cat B","Cat B","Cat C","Cat C","Cat C"),
COUNT = c(11,12,15,6,8,12,15,14,12)
)
df <- df %>%
mutate(
SPLIT2 = glue("{SPLIT} - {COUNT}")
)
ggplot(df, aes(YEAR, COUNT, label = COUNT, colour = SPLIT, group = SPLIT)) +
geom_line(size = 1) +
scale_x_continuous(labels = as.character(df$YEAR),
breaks =df$YEAR,
limits = c(min(df$YEAR),
max(df$YEAR+0.3)))+
geom_text_repel(data = subset(df, YEAR == max(YEAR)),
aes(label = SPLIT2),
show.legend = FALSE,
size = 4,
fontface = "bold",
hjust = "left",
nudge_x = 0.2,
direction = "y",
segment.color = NA) +
theme(legend.position="none")