ggplot2 facet标签与数据不对应

问题描述 投票:0回答:1

我是一个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)

其输出是:enter image description here

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

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

r ggplot2 facet
1个回答
1
投票

评论说。我认为你的ggplot调用“太复杂了”

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)

作品:enter image description here

编辑如果要重新排列构面,请将参数分解并更改级别的顺序。您可以在数据框(我不建议)或直接在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))
© www.soinside.com 2019 - 2024. All rights reserved.