0

I'm working in ggplot2. I was able to create a function. I want to do some modification as change the x-axis label colour based on a column vector (values 0 and 1).

plot <- function(df) {
   a <- ifelse(df$vector == 2, "red", "blue")
   ggplot(df, aes(ID, max_value)) +
   do stuffs  +
   theme(axis.text.x=element_text(angle=45, colour = a))
}

It works fine, until add the part colour = a , then I've got this warning

1: Vectorized input to `element_text()` is not officially supported.
Results may be unexpected or may change in future versions of ggplot2.  

And the plot only colour labels in red. Any idea about how to solve that?

2 Answers2

1

If you want to set the colors you have to condition on the breaks used for the x scale. But be aware that (as the warning says) vectorized arguments in the theme elements are not officially supported.

library(ggplot2)

d <- mtcars

breaks <- seq(50, 350, 50)
cols <- ifelse(breaks < 200, "red", "blue")

ggplot(mtcars, aes(hp, mpg)) +
  geom_point() +
  scale_x_continuous(breaks = breaks) +
  theme(axis.text.x = element_text(colour = cols))
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

stefan
  • 90,330
  • 6
  • 25
  • 51
  • the x-axis are IDs as "patient1", "patient2" ... and then, there is a column in the df which values (0 and 1) so if the patient1 is 0, I want in blue, if is 1 I want in red ... – Lila McPhee Nov 26 '21 at 11:36
  • Hi Lila. Would you mind making your issue reproducible, i.e. add a working code example to your post and a snippet of your data. To share your data type `dput(NAME_OF_DATASET)` in the console and copy the output into your post. If you have a lot of observations yould could do e.g. `dput(head(NAME_OF_DATASET, 20))` for the first 20 obs. – stefan Nov 26 '21 at 13:24
  • I think the new go to way would be {ggtext} - see also the suggested duplicate thread – tjebo Nov 30 '21 at 09:21
  • 1
    @tjebo. I agree. ggtext would be my go-to-guy, too. (; Still, occasionally I find the hack to pass a vector to the theme elements quite useful. Will close that one as a duplicate. – stefan Nov 30 '21 at 10:03
0

just add to aes(var1, colour = factor(column))

Mia Lua
  • 157
  • 1
  • 11
  • 1
    Hi Mia. Instead of just saying that adding a piece of code will solve the issue make your answer reproducible and show that it actually works. – stefan Nov 30 '21 at 17:28