在不同的图表上绘制不同的变量

Plot different variables on different graphs on top of each other

我有 3 个不同的变量(A、B、C)要绘制在 3 个图表上(因为它们有不同的轴)。我的输出在图表之间有很多 space,我想减少 space 并且在底部只有一个 X 轴,在所有图表上都有更宽的 y 限制。

我也读过 facet_wrap 是绘制多个图形的更好方法吗?你能给我建议什么是最好的吗?谢谢

我的数据:

Location = c(1,2,3,4,5,6,7)
A = c(1.16, 0.96, 0.67,0.78, 0.55, 0.3,0.26)
B = c(6.51, 4.98, 2.85, 3.19, 3.60, 10.82, 8.60)
C = c(75.45, 86.66, 103.36, NA, 107.53, NA, 128.49)

df = data.frame(Location, A, B, C)

我的代码:

par(mfrow=c(3,1))

plot(A, type = "l", col = "red", ylab = "A", main="Title", xlab = NULL)
plot(B, type = "l", col = "Blue", ylab = "B", xlab = NULL)
plot(C, type = "p", pch= 19, col = "Blue", ylab = "C", xlab = Location)

这里你有 x 标签 "Location" 就在最后

par(mfrow=c(3,1))

plot(A, type = "l", col = "red", ylab = "A", main="Title", xlab = "")
plot(B, type = "l", col = "Blue", ylab = "B", xlab = "")
plot(C, type = "p", pch= 19, col = "Blue", ylab = "C", xlab = "Location")

这是 facet_wrap 的选项。我稍微重组了你的数据。

df <- data.frame(Location = rep(Location, 3), y = c(A,B,C), letter = rep(c("A","B","C"), each = 7))

library(ggplot2)

ggplot(df, aes(x = Location, y = y, color = letter)) +
  geom_line() +
  geom_point() +
  scale_x_continuous(breaks = c(1:7), labels = c(1:7)) +
  facet_wrap(~letter, nrow = 3, scales = "free_y") +
  scale_color_manual(values = c("red", "blue", "blue")) + 
  theme(legend.position = "none")

这里使用 tidyr 包中的 pivot_longer 函数重塑数据框,这是一种略有不同的方法:

library(dplyr)
library(tidyr)
library(ggplot2)
df %>% pivot_longer(.,-Location, names_to = "var",values_to = "val") %>%
  filter(!is.na(val)) %>%
  ggplot(aes(x = Location, y = val, group = var, color = var))+
  geom_line()+
  ylab("")+
  facet_wrap(.~var, strip.position = "left", ncol = 1, scales = "free_y")+
  theme(strip.background = element_blank(),
        strip.placement = "outside")

编辑:仅更改小平面的比例

要仅更改 B 面的比例以使 y 值的范围从 0 到 40,您不能使用 scale_y_continuous,因为它将应用于所有面。

但是您可以做的是在数据框中为 B 组添加两个值为 0 和 40 的点,以强制 ggplot 在整个范围内绘制。然后,您可以将这部分的颜色设置为透明,以(在视觉上)将它们从绘图中移除:

df %>% pivot_longer(.,-Location, names_to = "var",values_to = "val") %>%
  filter(!is.na(val)) %>%
  mutate(NewVar = var) %>%
  add_row(., Location = c(1,1),
          var = c("B","B"),
          val = c(0,40),
          NewVar = c("Out","Out")) %>%
  ggplot(aes(x = Location, y = val, group = NewVar, color = NewVar))+
  geom_line()+
  ylab("")+
  facet_wrap(.~var, strip.position = "left", ncol = 1, scales = "free_y")+
  theme(strip.background = element_blank(),
        strip.placement = "outside")+
  scale_color_manual(values = c("red","green","blue","transparent"), breaks = c("A","B","C"))