强制因子变量的x轴限制与边界齐平

时间:2014-12-17 11:49:44

标签: r ggplot2

library(dplyr)
library(tidyr)
library(ggplot2)
dummy.data <- data.frame(
  X1 = c(1,2,-1,0),
  X2 = c(2,3,-2,-1),
  Month = c("January", "June", "January", "June"),
  Colour = c("A", "B", "B", "A")
  ) %>% 
  gather(key, value, X1:X2)

ggplot(dummy.data) + 
  geom_line(aes(x = Month, y = value, colour = Colour, group = Colour)) +
  facet_grid(~variable)

enter image description here

我想让1月份在每个小组的左边缘;六月在右边缘。彩色线的端点和面板的边缘之间不应有灰色条带。

1 个答案:

答案 0 :(得分:1)

您可以使用expand中的scale_x_discrete变量。请注意,您可能还需要调整标签,否则它们会重叠。您可以在hjust中使用theme来执行此操作:

ggplot(dummy.data) + 
  geom_line(aes(x = Month, y = value, colour = Colour, group = Colour)) +
  facet_grid(~variable) + 
  scale_x_discrete(expand=c(0,0)) +
  theme(axis.text.x = element_text(hjust=c(0, 1)))