user126082
user126082

Reputation: 310

Gghighlight won't display greyed lines in ggplot2 plot?

Sample of my dataset:

test <- structure(list(CCG = c("NHS DARLINGTON CCG", "NHS DARLINGTON CCG", 
"NHS DARLINGTON CCG", "NHS DARLINGTON CCG", "NHS DURHAM DALES, EASINGTON AND SEDGEFIELD CCG", 
"NHS DURHAM DALES, EASINGTON AND SEDGEFIELD CCG", "NHS DURHAM DALES, EASINGTON AND SEDGEFIELD CCG", 
"NHS DURHAM DALES, EASINGTON AND SEDGEFIELD CCG", "NHS GATESHEAD CCG", 
"NHS GATESHEAD CCG", "NHS GATESHEAD CCG", "NHS GATESHEAD CCG"
), value = c(0.98, 0.97, 0.97, 0.94, 0.96, 0.96, 0.96, 0.94, 
0.93, 0.92, 0.93, 0.94), metric = c("a", "b", "c", "d", "a", 
"b", "c", "d", "a", "b", "c", "d")), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

I'm trying to use the gghighlight package to highlight selected lines in my plot, as featured on the creator's site.

testplot <- test %>% 
  ggplot(aes(x=metric, y=value, group=CCG, colour=CCG)) + 
  geom_line() + 
  theme(legend.position="none")
testplot

Works fine if I want to colour all of my lines, however when I try and incorporate the gghighlight function into my graph, I get the error message:

testplot <- test %>% 
  ggplot(aes(x=metric, y=value, group=CCG, colour=CCG)) + 
  geom_line() + 
  gghighlight(CCG == "NHS DARLINGTON CCG", use_direct_label = FALSE) +
  theme(legend.position="none")
testplot

geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?

The selected line from the gghighlight call shows up but the rest have now disappeared instead of being faintly grey. I've already specified the group argument so I don't know what's going wrong.

Upvotes: 2

Views: 477

Answers (1)

markus
markus

Reputation: 26343

I guess the issue is related to the discrete scale in your plot and my attempt doesn't solve that but offers a workaround.

library(tidyverse)
library(gghighlight)
test %>% 
  group_by(CCG) %>% 
  mutate(idx = seq_along(metric)) %>% 
  ungroup() %>% 
  ggplot(aes(x = idx, y = value, group = CCG, colour = CCG)) + 
  geom_line() + 
  gghighlight(CCG == "NHS DARLINGTON CCG", use_direct_label = FALSE) +
  scale_x_continuous(labels = unique(test$metric)) +
  theme(legend.position = "none")

enter image description here

I simply created a numeric variable, idx, plotted it on the x-axis and used unique(test$metric) as axis labels in scale_x_continuous. Hope this helps.

Upvotes: 1

Related Questions