如何在ggplot中为每个组添加不同的行?

时间:2014-08-25 13:27:43

标签: r ggplot2

关于此主题已有几个问题(例如this one。我还找到了示例代码:

# another example; 1d
dat <- data.frame(x=rnorm(20), y=rnorm(20), z=rep(c("a", "b"), each=10))
vline.dat <- data.frame(z=levels(dat$z), vl=c(0,1))
q <- ggplot(dat, aes(x=x, y=y)) +
geom_point() +
geom_vline(aes(xintercept=vl), data=vline.dat) +
facet_grid(z~.)

代码产生了这个数字:Resulting figure of above code

我有,但是没有弄清楚我的数据有什么不同以及为什么它现在正在工作。 我有以下数据框:

"yaw" "stimulus"
27.927177 30
27.4999279999999 30
-0.5536 90
56.97471 90
65.0127040816326 90
62.33216 90
74.87201 90
67.5808163265306 90
-2.948312 90
68.52282 90
54.9006326530612 90
60.4753 90
64.53204 90
3.2848 45
26.87405 45
50.8667040816327 45
59.62888 45
53.9892244897959 45
61.27226 45
71.79869 45
88.7793775510204 45
77.78727 45
79.73406 45
104.542 45
114.92185 45
140.76407 45
131.187357142857 45
169.08197 45
-137.36238 45
-147.789030612245 45
5.7612 60
8.7396 60
-1.06195918367347 60
4.52126 60
10.05313 60
10.8253469387755 60
9.49371 60
29.9075 60
28.0361530612245 60
-9.32023 60
-57.9522755102041 60
-61.5898 60
-66.23353 60
-53.1884387755102 60
-40.41378 60
-16.734 60
-5.66388 60
3.58145 60

条形图的数据框如下所示:

stimuli <- data.frame(groups = c(90, 60, 45, 30),
         pos = c(-90, 60, 45, 30))

我的绘图代码如下所示:

fig <- ggplot(df, aes(yaw, group = stimulus)) +
geom_histogram(binwidth = 1, aes(y = 0.5 * ..density..)) +
   scale_x_continuous(breaks = c(-180, -90, 0, 90, 180)) +
   ylab("Count") + xlab("Yaw Angle [º]") +
facet_grid(stimulus ~ .) +
# add vertical lines at the bar positions
geom_vline(data = stimuli, aes(xintercept = pos, colour = "red"))

My figure 每个构面应仅包含一个红色垂直条。你能指出我的错误吗?

1 个答案:

答案 0 :(得分:1)

只需重命名stimuli中的列(因此facet_grid会将其识别为分面变量):

names(stimuli)[1] <- "stimulus"


library(ggplot2)
fig <- ggplot(DF, aes(yaw)) +
  geom_histogram(binwidth = 1, aes(y = 0.5 * ..density..)) +
  scale_x_continuous(breaks = c(-180, -90, 0, 90, 180)) +
  ylab("Count") + xlab("Yaw Angle [º]") +
  facet_grid(stimulus ~ .) +
  # add vertical lines at the bar positions
  geom_vline(data = stimuli, aes(xintercept = pos), colour = "red")

print(fig)

resulting plot