我有两个数据集,如下所示:
> 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和gather绘制了这些数据:
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 处的 y 截距线(对于这个数据集看不到它们,但我有其他更大的集合,其中 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))
使用此示例:如何为面添加不同的线条但这让我在所有面中获得了所有线条,但这不是我想要的。
怎样才能做到(以及能做到吗)?
除了上面用于向 geom_line 发送一个/几个值的 Jon Springs 解决方案之外,如果要添加很多行(例如,如果显示多个元素分析并想要向某些元素添加不同的检测级别),还有一种解决方案:
ggplot(gather(df, key=KeyVector, value="value", ),
aes(y=value, x=Xvalues, color=ColValues, shape=ShapeValues)) +
geom_point() +
#geom_histogram() +
facet_wrap(~ KeyVector, scales = 'free') +
geom_hline(data = tibble(KeyVector, y = unlist(HlineValues)), aes(yintercept=y) )
> dput(KeyVector)
c("Al", "Ca", "Fe", "K", "Mg", "Mn", "Na", "P", "Si", "Ti")
> dput(HlineValues)
structure(list(Al = NA_real_, Ca = NA_real_, Fe = 0.00699430761427042,
K = NA_real_, Mg = NA_real_, Mn = 0.00774461846427111, Na = NA_real_,
P = 0.00436426817378561, Si = NA_real_, Ti = 0.00599348901270895), class = "data.frame", row.names = "y")
为了让与我有类似知识的其他人清楚,变量 HlineValues 是一个具有一行的数据框(包含成为 hline 的数据),其长度必须与 KeyVector 相同,colnames(HlineValues) 与在 KeyVector 中。