简体   繁体   中英

facet_grid: modify x axis label for each facet

I am unable to modify the x axis labels on the second facet. The ones for the first facet are fine but how to make the ones for the second facet to be - 119 , 121 , 130 , 133 ?

我的数字与第二个方面的x轴标签不正确

Here is my code:

data$treatment <- factor(data$treatment, levels = c("baseline", "3m"))
labels<- c(`baseline` = "Baseline",`3m` = "3 m after") 

p <- ggplot(data = data, aes(x = day, y = BL.P, group = mechanism)) +
geom_line(aes(color = mechanism), size = 1) +
geom_point(aes(color = mechanism), size = 3) +
scale_color_manual(values = c("#CC79A7", "#0072B2", "#000000"), 
                   name = "Mechanism") + 
labs(title = "Title", x = "Day", y = "Proportion (%)") +


p + facet_grid(~treatment, scales = "free_x", space = "free_x", 
               labeller = labeller(treatment = labels)) +  
    scale_x_continuous(breaks = seq(1,21,by = 1), 
                       labels = c("1","3","5","8","10","15","17","19","22","24",
                                  "26","29","31","33","36","38","40","43","45",
                                  "47","50")) +
    theme(strip.text.x = element_text(size = 12, face = "bold"))    

Here is my data: https://www.dropbox.com/s/kppvgucdwa20otd/data.csv?dl=0

I am a complete R beginner and this is one of my first figures. I would very much appreciate a simple solution if possible...

Here's one quick&dirty way to do it (there may be better options):

library(ggplot2)
download.file("https://www.dropbox.com/s/kppvgucdwa20otd/data.csv?dl=1", tf <- tempfile(fileext = ".csv"))
data <- read.csv(tf)
data$treatment <- factor(data$treatment, levels = c("baseline", "3m"))
labels<- c(`baseline`="Baseline",`3m`="3 m after") 

data2 <- data
data2$day[data2$treatment=="3m"] <- c("1"="119","3"="121","5"="130","8"="133")[data2$day[data2$treatment=="3m"]]
data2$day[data2$treatment=="baseline"] <- structure(c("1", "3", "5", "8", "10", "15", "17", "19", "22", 
"24", "26", "29", "31", "33", "36", "38", "40", "43", "45", "47", 
"50"), .Names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", 
"21"))[data2$day[data2$treatment=="baseline"]]
data2$day <- factor(data2$day, levels = sort(as.numeric(unique(data2$day))))

ggplot(data=data2, aes(x=day, y=BL.P, group=mechanism)) +
  geom_line(aes(color=mechanism), size=1)+
  geom_point(aes(color=mechanism), size=3)+
  scale_color_manual(values=c("#CC79A7", "#0072B2", "#000000"), name="Mechanism")+ 
  labs(title="Title",x="Day", y = "Proportion (%)") + 
  facet_grid(~treatment, scales = "free_x", space = "free_x",labeller=labeller(treatment = labels)) +  
  theme(strip.text.x = element_text(size=12, face="bold")) 

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