简体   繁体   中英

Individually change x labels using expressions in ggplot2 boxplot with facet_grid in R

I want to individually change the x labels of my ggplot2 boxplot when using a facet_grid. I made the following simple example:

library(ggplot2)

data1 <- InsectSprays
data1$group <- "group 1"
data2 <- InsectSprays
data2$group <- "group 2"

plotData <- rbind(data1, data2)

ggplot(plotData, aes(x=spray, y=count, fill=spray))+
guides(fill=FALSE) +
facet_grid(. ~ group) +
geom_boxplot()

在此处输入图片说明

I want to change the labels on the x axis (A, B, C,...), but individually for the two groups. One way changing the labels would be, using:

scale_x_discrete(labels=c("label 1", "label 2", ...))

but this would change the labels in both groups to the same values. At the end I also need to be able to use expressions for the labels. Is there any way to achieve what I want?

EDIT:

There is a very simple way to solve my problem (thanks @Axeman). By using:

scale_x_discrete(labels=c('A' = expression(beta)))

I can change the labels. In my example this would change both groups, but for me it is possible to rename the labels to individual labels beforehand and than use this trick to use expressions for the labels.

plotData$x <- interaction(plotData$spray, plotData$group)
plotData$x <- factor(plotData$x, labels = paste('labels', 1:12))

ggplot(plotData, aes(x=x, y=count, fill=spray))+
    geom_boxplot(show.legend = FALSE) +
    facet_grid(. ~ group, scales = 'free')

在此处输入图片说明

I would have expected the following to work, but it doesn't!

ggplot(plotData, aes(x=interaction(spray, group), y=count, fill=spray))+
  geom_boxplot(show.legend = FALSE) +
  facet_grid(. ~ group, scales = 'free') +
  scale_x_discrete(labels = paste('labels', 1:12))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM