![](/img/trans.png)
[英]starting the y-axis at a minimum value, the x-axes at 0, and making them intersect using matplot() in R
[英]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.