【发布时间】:2017-12-23 02:25:03
【问题描述】:
这个问题的目的是:如何使用ggplot在图例框中分别组合点和线。这是我的数据集:它由两个不同模型的时间、实际数据点和预测数据点组成
time <- seq(2009.25, 2016, by=0.25)
act.data <- c(0, 0, 1, 15, 29, 42, 59, 79, 93, 135, 159, 181, 194, 208, 216, 225,
272, 285, 308, 325, 331, 338, 348, 361, 396, 429, 481, 508)
pred.data_1 <- c(26.94136, 31.92765, 37.76609, 44.57464, 52.47702, 61.59878, 72.06163,
83.97596, 97.43151, 112.48662, 129.15672, 147.40328, 167.12485, 188.15196,
210.24759, 233.11426, 256.40805, 279.75825, 302.79059, 325.15084, 346.52585,
366.65943, 385.36152, 402.51061, 418.05014, 431.98047, 444.34828, 455.23510)
pred.data_2 <- c(25.54623, 33.01310, 41.26586, 50.30449, 60.12899, 70.73938, 82.13564,
94.31777, 107.28579, 121.03968, 135.57944, 150.90509, 167.01661, 183.91400,
201.59728, 220.06643, 239.32146, 259.36236, 280.18914, 301.80180, 324.20034,
347.38475, 371.35504, 396.11120, 421.65324, 447.98116, 475.09496, 502.99463)
data.frame(
time=time,
pred_1=pred.data_1,
pred_2=pred.data_2,
act.daa=act.data
) -> xdf
我想使用两个模型的预测值根据不同的颜色线和使用点的实际数据点来生成我的图表。代码如下:
cols <- c("AM"="#000000", "RL"="#0000FF")
br_x <- seq(2009, 2016, by=1)
br_y <- seq(1, 525, by=125)
ggplot(xdf, aes(time, act.data)) +
geom_point() +
geom_line(aes(y=pred_1, colour="AML"), size=0.2) +
geom_line(aes(y=pred_2, colour="RL"), size=0.2) +
scale_x_continuous(name="Year", breaks=br_x) +
scale_y_continuous(name="Cumulative Data", breaks=br_y) +
scale_colour_manual(name="MODEL", values=cols) +
theme_bw()+
theme(axis.title = element_text(face="bold"),
legend.position = c(0.3,0.95),
legend.justification = c("right","top"),
legend.box.just = "left")
运行此代码后,图例中会出现两条不同颜色的线,但黑点不会出现。我想制作由 2 条具有不同颜色的线和独立代表实际数据点的点组成的图例。
【问题讨论】:
-
我修复了非运行代码,但你也有错别字,我没有修复。 Jazurro 在答案中修复了它们。
-
@hrbrmstr 感谢您整理代码。 :) 我实际上也在研究它。圣诞快乐!