[英]Plotting points and lines separately in R with ggplot
我正在嘗試使用ggplot繪制R中的2組數據點和單行。 我遇到的問題是傳說。 從附圖中可以看出,圖例將線條應用於所有3個數據集,即使其中只有一個用線條繪制。
我已將數據融合到一個長幀中,但這仍然需要我為每個單獨調用geom_line()
和geom_path()
過濾數據集。
我想繪制融化數據的圖形,根據一個數據集繪制一條線,然后使用完整的圖例指向其余兩個數據集。
這是我為編寫劇情而編寫的示例腳本:
xseq <- 1:100
x <- rnorm(n = 100, mean = 0.5, sd = 2)
x2 <- rnorm(n = 100, mean = 1, sd = 0.5)
x.lm <- lm(formula = x ~ xseq)
x.fit <- predict(x.lm, newdata = data.frame(xseq = 1:100), type = "response", se.fit = TRUE)
my_data <- data.frame(x = xseq, ypoints = x, ylines = x.fit$fit, ypoints2 = x2)
## Now try and plot it
melted_data <- melt(data = my_data, id.vars = "x")
p <- ggplot(data = melted_data, aes(x = x, y = value, color = variable, shape = variable, linetype = variable)) +
geom_point(data = filter(melted_data, variable == "ypoints")) +
geom_point(data = filter(melted_data, variable == "ypoints2")) +
geom_path(data = filter(melted_data, variable == "ylines"))
pushViewport(viewport(layout = grid.layout(1, 1))) # One on top of the other
print(p, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
您可以像這樣手動設置它們:
我們為第一項設置linetype =“solid”,為其他項設置“blank”(無行)。
類似地,對於第一項,我們沒有設置形狀(NA),而對於其他項目,我們將設置我們需要的任何形狀(我只是將7和8放在那里作為示例)。 請參閱http://www.r-bloggers.com/how-to-remember-point-shape-codes-in-r/,以幫助您根據需要選擇正確的形狀。
如果您對點滿意,那么您可以使用my_shapes = c(NA,16,16)
並且scale_shape_manual(...)
。
my_shapes = c(NA,7,8)
ggplot(data = melted_data, aes(x = x, y = value, color=variable, shape=variable )) +
geom_path(data = filter(melted_data, variable == "ylines") ) +
geom_point(data = filter(melted_data, variable %in% c("ypoints", "ypoints2"))) +
scale_colour_manual(values = c("red", "green", "blue"),
guide = guide_legend(override.aes = list(
linetype = c("solid", "blank","blank"),
shape = my_shapes))) +
scale_shape_manual(values = my_shapes)
但是我很好奇是否有更自動化的方式。 希望有人可以發布更好的答案。
這篇文章非常依賴於這個答案: ggplot2:點和線的不同圖例符號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.