1

I cannot order the y value!

Here is an example:

#Create a demo data set:

df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                  dose=rep(c("D0.5", "D1", "D2"),2),
                  len=c(6.8, 15, 33, 4.2, 10, 29.5))
print(df2)

##   supp dose  len
## 1   VC D0.5  6.8
## 2   VC   D1 15.0
## 3   VC   D2 33.0
## 4   OJ D0.5  4.2
## 5   OJ   D1 10.0
## 6   OJ   D2 29.5

#Plot y = “len” by x = “dose” and change color by a second group: “supp”

#Interleaved (dodged) bar plot
ggbarplot(df2, x = "dose", y = "len",
          fill = "supp", color = "supp", 
          palette = c("gray", "black"),
          position = position_dodge(0.9))

I added sort.val = "desc" to adjust the order of the y- value in the graphic:

ggbarplot(df2, x = "dose", y = "len",
          fill = "supp", color = "supp", 
          palette = c("gray", "black"), sort.val = "desc" ,
          position = position_dodge(0.9)) 

the result is an error:

Error in `levels<-`(`*tmp*`, value = as.character(levels)) : 
  factor level [4] is duplicated

What can I do?

  • 1
    I think the `sort.val` argument does not exactly do what one expects. It requires unique values for your x, but then also doesn't really sort it. I personally don't find `ggpubr` very helpful here - would suggest to follow the link posted and create a "classic" ggplot barchart – tjebo Jan 27 '20 at 16:20

1 Answers1

3

This doesn't use ggbarplot but might get you what you're looking for, which I'm guessing is putting VC ahead of OJ:

library(tidyverse)

df2 %>% 
  mutate(supp = factor(supp, levels = c("VC", "OJ"))) %>% 
  ggplot(aes(x = dose, y = len, fill = supp)) +
  geom_col(position = "dodge") +
  scale_fill_manual(values = c("gray50", "black"))

The key line is #2, which manually relevels the factors in supp in the order we want.

cardinal40
  • 1,245
  • 1
  • 9
  • 11