【发布时间】:2018-03-14 17:24:03
【问题描述】:
我想画四条线,下面是随机生成的数据:
trE <- runif(12, 0.5, 0.8)
teE <- runif(12, 0.8, 1)
trES <- runif(12, 0, 0.3)
teES <- runif(12, 0.3, 0.5)
plotData <- data.frame(k=1:12, trE=trE, teE=teE, trES=trES, teES=teES)
我已经使用下面的代码绘制了它:
ggplot(plotData, aes(k)) +
geom_line(aes(y = trE, colour = "Tr E")) +
geom_line(aes(y = teE, colour = "Te E")) +
geom_line(aes(y = trES, colour = "Tr ES"), linetype="dashed") +
geom_line(aes(y = teES, colour = "Te ES"), linetype="dashed") +
geom_hline(aes(yintercept = 0.5), linetype="dotted",colour='red') +
scale_colour_manual(values=c("black", "orange","black", "orange"),
labels=c("Tr E", "Te E", "Tr ES", "Te ES")) +
scale_x_discrete(limits=1:12) +
theme_bw()
但输出却不如预期:
线条颜色乱七八糟,在图中应该是“橙色”、“黑色”、“橙色”、“黑色”的顺序。
ggplot(plotData, aes(k)) +
geom_line(aes(y = trE, colour = "black")) +
geom_line(aes(y = teE, colour = "orange")) +
geom_line(aes(y = trES, colour = "black"), linetype="dashed") +
geom_line(aes(y = teES, colour = "orange"), linetype="dashed") +
geom_hline(aes(yintercept = 0.5), linetype="dotted",colour='red') +
scale_colour_manual(values=c("black", "orange","black", "orange"),
labels=c("Tr E", "Te E", "Tr ES", "Te ES")) +
scale_x_discrete(limits=1:12) +
theme_bw()
但是,在此图中,线条颜色与预期一致,但标签与预期不同。
你对这种奇怪的行为有什么想法吗?或指出我缺少的细节。
更新:
plotDataLong <- plotData %>% tidyr::gather(Error, value, 2:5)
ggplot(plotDataLong, aes(k, value, col=Error)) + geom_line() +
geom_hline(aes(yintercept = 0.5), linetype="dotted",colour='red') +
scale_colour_manual(values=c("black", "orange","black", "orange"),
labels=c("Tr E", "Te E", "Tr ES", "Te ES")) +
scale_linetype(labels=c("solid","solid","dashed","dashed"))
虽然代码大大简化了,但线型却不尽如人意。
【问题讨论】:
-
错误是什么?
-
在使用 ggplot 之前整理你的数据 (
tidyr::gather) 要好得多。大大简化了代码