首页 > 解决方案 > 在收集:ed 数据的 facet_wrap 中向某些方面添加不同的行

问题描述

我有两个数据集,如下所示:

> str(Maj.plot)
'data.frame':   70 obs. of  13 variables:
 $ Sample  : chr  "Kx V17" "Mu V17" "Ob V17" "Vä V17" ...
 $ Mill    : chr  "Karlsborg" "Munksund" "Obbola" "Väja" ...
 $ Halfyear: chr  "S17" "S17" "S17" "S17" ...
 $ Al      : num  0.355 0.593 0.804 0.318 0.847 ...
 $ Ca      : num  17.6 14.1 15.1 24 14.1 ...
 $ Fe      : num  0.315 0.455 0.413 0.224 0.776 ...
 $ K       : num  0.639 0.473 0.324 0.955 0.216 ...
 $ Mg      : num  5.36 9.51 10.36 2.84 12.25 ...
 $ Mn      : num  1.46 3.11 3.2 1.49 4.25 ...
 $ Na      : num  7.08 5.31 2.23 8.45 2.79 ...
 $ P       : num  0.096 0.144 0.144 0.6023 0.0829 ...
 $ Si      : num  0.767 0.467 1 1.271 3.613 ...
 $ Ti      : num  NA NA NA NA 0.018 ...

> str(DL.major)
'data.frame':   1 obs. of  10 variables:
 $ Al: num NA
 $ Ca: num NA
 $ Fe: num 0.00699
 $ K : num NA
 $ Mg: num NA
 $ Mn: num 0.00774
 $ Na: num NA
 $ P : num 0.00436
 $ Si: num NA
 $ Ti: num 0.00599

我已经用 facet_wrap 和收集绘制了这些数据:

ggplot(gather(Maj.plot, key=Element.major, value="value",  -"Sample", -"Mill", -"Halfyear"),
                  aes(y=value, x=Mill, color=Mill, shape=Halfyear))  + 
  geom_point() + 
  facet_wrap(~ Element.major, scales = 'free', ncol=3) 

添加到此情节中的还有主题、ggtitel() 和指南等未在此处显示的内容(不确定它是否会影响答案)。

我想要的是在某些方面添加不同的行,例如数据集 DL 中的 geom_hline()。

例如,对于名称为 Fe 的刻面,我想要 y= 0.00699 处的 yintercept 线(对于这个数据集看不到它们,但我有其他更大的集,其中 y 的比例足够小,以至于线将可见)。但没有针对 Al 面的线。

我试过了:

ggplot(gather(Maj.plot, key=Element.major, value="value",  -"Sample", -"Mill", -"Halfyear"),
                  aes(y=value, x=Mill, color=Mill, shape=Halfyear))  + 
  geom_point() + 
  facet_wrap(~ Element.major, scales = 'free', ncol=3) +
  geom_hline(data= DL.major)

但是 geom_hline 需要一个来设置 yintercept 我不知道在那里指定什么所以没有用。我也试过:

DL.major.1 <-t(DL.major)
colnames(DL.major.1) <- "DL"

ggplot(gather(Maj.plot, key=Element.major, value="value",  -"Sample", -"Mill", -"Halfyear"),
                  aes(y=value, x=Mill, color=Mill, shape=Halfyear))  + 
  geom_point() + 
  facet_wrap(~ Element.major, scales = 'free', ncol=3) +
  geom_hline(data= DL.major.1, aes(yintercept = DL))

使用此示例:如何为构面添加不同的线条但这让我在所有方面都获得了所有线条,这不是我想要的。

怎么做(并且可以做到)?

标签: rggplot2

解决方案


也许是这样的?

(顺便说一句,通过使用内置数据集或通过使用dput(YOUR_DATA)或提供生成它的代码包含与您类似的结构化数据样本,使您的问题可重现是一种很好的做法。)

mtcars %>%
  ggplot(aes(wt, mpg)) +
  geom_point() +
  #important, this should have the faceted variable
  geom_hline(data = tibble(gear = 3, y = 30), aes(yintercept = y)) +
  facet_wrap(~gear)

在此处输入图像描述


推荐阅读