Boxplot one x axis tick mark label for two boxes

2020-04-21 01:50发布

问题:

I'm trying to create a boxplot using ggplot2 in R, below is my code and the plot it produces. I want to change it so instead of having the x axis labelled as 0.5mg, 0.5mg, 1mg, 1mg, 2mg and 2mg, I want just 0.5mg, 1mg, and 2mg between each of the sets of two box plots. Is there any way to do this?

ggplot(ToothGrowth, aes(x=interaction(supp, dose), y=len, fill=supp)) + 
geom_boxplot() +
scale_x_discrete(labels = c("0.5mg", "0.5mg", "1mg", "1mg", "2mg", "2mg"), name = "Dosage") +
scale_y_continuous(name = "Tooth Length") + 
scale_fill_discrete(name = "Supplement",
                    labels = c("Orange Juice", "Ascorbic Acid"))

回答1:

library(ggplot2)
ggplot(ToothGrowth, aes(x= as.factor(dose), y=len, fill=supp)) + 
  geom_boxplot() +
  scale_x_discrete(name = "Dosage", labels = function(x) {paste0(x, "mg")}) + 
  scale_y_continuous(name = "Tooth Length") + 
  scale_fill_discrete(name = "Supplement",
                    labels = c("Orange Juice", "Ascorbic Acid"))

Result:



标签: r ggplot2