簡體   English   中英

R ggplot facet - 共享y軸,多個不同的x軸

[英]R ggplot facet — shared y axis, multiple distinct x-axes

我有一個由3個變量(a,b,c)和一個響應(d)組成的數據集。

    df <- structure(list(a = c(0.9973, 0.9965, 1.002, 1.0019, 1.001, 1.0031, 
1.0005, 1.0009, 1.0007, 0.9977, 1.0004, 1.001, 0.9936, 0.9945, 
1.0056, 1.0004, 0.9969, 0.9977, 1.001, 0.9876), b = c(-4.0841, 
-4.216, -4.1469, -4.1418, -4.1919, -4.1953, -4.3314, -4.1205, 
-4.2449, -4.0841, -4.276, -4.3396, -4.2885, -4.1386, -4.0689, 
-4.2229, -4.3886, -4.2267, -4.0344, -4.6152), c = c(32.04, 18.52, 
26.01, 25.65, 21.44, 22.26, 21.8, 21.6, 17.38, 13.84, 20.19, 
27.66, 20.85, 18.71, 22.18, 17.25, 26.78, 28.08, 25.9, 16.68), 
    d = c(2241, 2231, 2231, 2220, 2218, 2216, 2210, 2204, 
    2202, 2194, 2157, 2028, 1853, 1850, 1770, 1755, 1679, 
    1673, 1673, 1645)), .Names = c("a", "b", "c", "d"), class = "data.frame", row.names = c(NA, 
-20))

我的目標是在ggplot2使用facet來創建一個共同的y軸為d的圖,以及分別具有a,b和c的x軸的三個面 - 換句話說,d vs a,d vs. b ,以及d與c相鄰,具有共同的y軸。 我的目標的近似值可以在基數R中顯示:

par(mfrow=c(1,3))
plot(df$a, df$d)
plot(df$b, df$d)
plot(df$c, df$d)

我想用ggplot這樣做而不重復y軸。 我見過類似的情節,但它們通常涉及一次重復幾次的x軸。 我試圖melt數據(即來自reshape2 ),但我還沒有提出適合我的方向。

在視覺上也希望d對a,d對b和d對c中的每一個都是不同的顏色。

在此先感謝您的幫助!

你走在正確的軌道上。 我們需要將df轉換為長格式(例如tidyr::gather )然后使用ggplot::facet_grid來獲得所需的繪圖

df <- structure(list(a = c(0.9973, 0.9965, 1.002, 1.0019, 1.001, 1.0031, 
  1.0005, 1.0009, 1.0007, 0.9977, 1.0004, 1.001, 0.9936, 0.9945, 
  1.0056, 1.0004, 0.9969, 0.9977, 1.001, 0.9876), b = c(-4.0841, 
  -4.216, -4.1469, -4.1418, -4.1919, -4.1953, -4.3314, -4.1205, 
  -4.2449, -4.0841, -4.276, -4.3396, -4.2885, -4.1386, -4.0689, 
  -4.2229, -4.3886, -4.2267, -4.0344, -4.6152), c = c(32.04, 18.52, 
  26.01, 25.65, 21.44, 22.26, 21.8, 21.6, 17.38, 13.84, 20.19, 
  27.66, 20.85, 18.71, 22.18, 17.25, 26.78, 28.08, 25.9, 16.68), 
      d = c(2241, 2231, 2231, 2220, 2218, 2216, 2210, 2204, 
      2202, 2194, 2157, 2028, 1853, 1850, 1770, 1755, 1679, 
      1673, 1673, 1645)), 
  .Names = c("a", "b", "c", "d"), 
  class = "data.frame", row.names = c(NA,-20))

library(tidyverse)

df_long <- df %>% 
  gather(key, value, a:c)

ggplot(df_long, aes(x = d, y = value, color = key)) +
  geom_point() +
  facet_grid(~ key) +
  theme_bw()

ggplot(df_long, aes(x = d, y = value, color = key)) +
  geom_line() +
  facet_grid(~ key)+
  theme_bw()

ggplot(df_long, aes(x = d, y = value, color = key, fill = key)) +
  geom_col() +
  facet_grid(~ key)+
  theme_bw()

reprex包創建於2018-06-07 (v0.2.0)。

謝謝Tung和Amanda讓我走上正軌。 關鍵是使用facet_wrap而不是facet_grid 一旦數據采用上述適當的長格式:

library(tidyverse) 
df_long <- df %>% 
   gather(key, value, a:c)

然后這個版本的訣竅:

ggplot(df_long, aes(x = value, y = d, color = key)) +
    geom_point() +
    facet_wrap(~ key, scales="free_x")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM