ggplot2 刻面标签与数据不对应

ggplot2 facet labels don't correspond to data

我是 R 新手,我可能遗漏了一些微不足道的东西,但就是这样:

我有一个数据框 Data,其值如下:

         Voltage Current  lnI     VoltageRange
    1    0.474   0.001 -6.907755  Low Voltage
    2    0.883   0.002 -6.214608  Low Voltage
    3    1.280   0.005 -5.298317  Low Voltage
    .      .       .        .          .
    .      .       .        .          .
    .      .       .        .          .
    .      .       .        .          .
   13    2.210   0.247 -1.398367 High Voltage

然后我尝试用下面的代码绘制它:

ggplot(data = Data, mapping = aes(x = Data$lnI, y = Data$Voltage)) +
      geom_point() +
      stat_smooth(method = "lm", se = FALSE) +
      facet_grid(~VoltageRange)

其输出为:

如您所见,刻面标签放错了位置,标记为高压的对应低压,反之亦然。

我该如何解决这个问题?我做错了什么?

如评论所述。我认为你的 ggplot 调用是 'too complicated'

require(read.so) #awesome package available on GitHub, by @alistaire47 
dat <- read_so() 
dat <- dat[c(1:3,8),] 

dat
# A tibble: 4 x 4
  Voltage Current lnI       VoltageRange
  <chr>   <chr>   <chr>     <chr>       
1 0.474   0.001   -6.907755 Low         
2 0.883   0.002   -6.214608 Low         
3 1.280   0.005   -5.298317 Low         
4 2.210   0.247   -1.398367 High 

ggplot(dat, aes(x = lnI, y = Voltage)) + # remove 'mapping', 
# and use only the object names, not the columns/ vectors
  geom_point() + 
  stat_smooth(method = "lm", se = FALSE) +
  facet_grid(~VoltageRange)

作品:

编辑 如果要 re-arrange 方面,请分解参数并更改级别的顺序。您可以在数据框中(我不推荐这样做)或直接在 ggplot 调用中执行此操作。为此,我发现创建一个具有级别顺序的字符向量很好,因为您可能再次需要这个。

facet_order <- c('Low', 'High') 
# note it's important that the levels are written exactly the same
ggplot(dat, aes(x = lnI, y = Voltage)) + 
      stat_smooth(method = "lm", se = FALSE) +
      facet_grid(~factor(VoltageRange, levels = facet_order))