facet_grid:修改每个构面的x轴标签

时间:2017-01-09 19:10:51

标签: r ggplot2

我无法修改第二个方面的x轴标签。第一个方面的方法很好但是如何使第二个方面的方法为 - 119121130133

My figure with the incorrect x axis labels for the second facet

这是我的代码:

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"))    

这是我的数据: https://www.dropbox.com/s/kppvgucdwa20otd/data.csv?dl=0

我是一个完整的R初学者,这是我的第一个数字之一。如果可能的话,我非常感谢一个简单的解决方案...

1 个答案:

答案 0 :(得分:0)

这是一种快速而又肮脏的方式(可能有更好的选择):

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"))