我需要制作一個包含多種資料的圖表,并且我正在用線繪制一種資料,用點繪制一種資料。我添加了一個手動指定的圖例來顯示哪種型別是點,哪種是線(誠然,我的方法有點老套),除了圖例順序外,它都有效。這是一個虛擬示例:
DF1 <- data.frame(X = 1:10,
Y = c(1:10*0.5, 1:10*0.25),
Fruit = rep(c("mango", "kiwi"), each = 10))
DF2 <- data.frame(X = 1:10,
Y = c(1:10*2, 1:10*4),
Cat = rep(c("tabby", "calico"), each = 10))
Empty <- data.frame(X = mean(DF$X),
Y = as.numeric(NA),
# Q = c(0, 1))
Type = c("Cat", "Fruit"))
Mygraph <- ggplot(DF1, aes(x = X, y = Y, color = Fruit))
geom_point()
geom_line(data = DF2, aes(x = X, y = Y, linetype = Cat),
inherit.aes = F)
labs(color = NULL, linetype = NULL)
geom_point(data = Empty, aes(x = X, y = Y, alpha = Type),
inherit.aes = F)
geom_line(data = Empty, aes(x = X, y = Y, alpha = Type),
inherit.aes = F)
scale_alpha_manual(
name = "Type of item", values = c(1, 1),
breaks = c("Fruit", "Cat"),
guide = guide_legend(override.aes =
list(linetype = c("blank", "solid"),
shape = c(16, NA))))
theme_bw()
Mygraph
這張圖看起來不錯:

但是,當我嘗試指定訂單時,請查看“專案型別”位會發生什么情況:
Mygraph
guides(alpha = guide_legend(order = 1),
linetype = guide_legend(order = 2),
color = guide_legend(order = 3))

為什么我指定的美學消失了?如何既指定圖例的該部分應該是什么樣子,又指定圖例的三個部分的順序應該是 1. alpha、2. linetype 和 3. color?
uj5u.com熱心網友回復:
您試圖在兩個地方(即guides()和scale_alpha...())覆寫 alpha 的美學,而 ggplot 選擇只解釋其中一個。我建議在您的圖例順序覆寫中包含您的形狀覆寫,如下所示:
library(ggplot2)
ggplot(DF1, aes(x = X, y = Y, color = Fruit))
geom_point()
geom_line(data = DF2, aes(x = X, y = Y, linetype = Cat), inherit.aes = F)
labs(color = NULL, linetype = NULL)
geom_point(data = Empty, aes(x = X, y = Y, alpha = Type), inherit.aes = F)
geom_line(data = Empty, aes(x = X, y = Y, alpha = Type), inherit.aes = F)
scale_alpha_manual(name = "Type of item", values = c(1, 1), breaks = c("Fruit", "Cat"))
guides(alpha = guide_legend(order = 1,
override.aes=list(linetype = c("blank", "solid"),
shape = c(16,NA))),
linetype = guide_legend(order = 2),
color = guide_legend(order = 3))
theme_bw()

資料:
DF1 <- data.frame(X = 1:10,
Y = c(1:10*0.5, 1:10*0.25),
Fruit = rep(c("mango", "kiwi"), each = 10))
DF2 <- data.frame(X = 1:10,
Y = c(1:10*2, 1:10*4),
Cat = rep(c("tabby", "calico"), each = 10))
Empty <- data.frame(X = mean(DF1$X),
Y = as.numeric(NA),
Type = c("Cat", "Fruit"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482752.html
上一篇:如何將點值寫入R中的線圖?
