[英]R: ggplot2 removing some legend entries
require(reshape2);require(ggplot2)
df <- data.frame(time = 1:10,
x1 = rnorm(10),
x2 = rnorm(10),
x3 = rnorm(10),
y1 = rnorm(10),
y2 = rnorm(10))
df <- melt(df, id = "time")
ggplot(df, aes(x = time, y = value, color = variable, group = variable,
size = variable, linetype = variable)) +
geom_line() +
scale_linetype_manual(values = c(rep(1, 3), 2, 2)) +
scale_size_manual(values = c(rep(.3, 3), 2, 2)) +
scale_color_manual(values = c(rep("grey", 3), "red", "green")) +
theme_minimal()
這個例子可能不是很具有代表性,但是,例如,假設運行一堆回歸模型,這些回歸模型分別並不重要,而只是有助於整體發展。 雖然我只想強調實際和平均擬合系列。 因此,基本上變量x不重要,因此不應出現在圖例上。
我試圖按照其他一些帖子中的建議設置scale_color_discrete(breaks = c("y1", "y2"))
。 但是問題在於,所有美學已經通過手冊使用,並且嘗試設置另一個離散版本將覆蓋已經為圖形設置的屬性(並弄亂了整個事物)。 因此,理想情況下-我希望看到完全相同的圖形,但圖例中僅顯示y1和y2。
您可以嘗試通過變量名稱對數據集進行子集設置,然后分別進行繪制。
p <- ggplot(df, aes(x = time, y = value, color = variable,
group = variable, size = variable, linetype = variable)) +
geom_line(data=df[which(substr(df$variable,1,1)=='y'),])+
scale_linetype_manual(values = c(2, 2)) + scale_size_manual(values = c(2, 2)) +
scale_color_manual(values = c("red", "green")) +
theme_minimal() +
geom_line(data=df[which(substr(df$variable,1,1)=='x'),],
aes(x = time, y = value, group = variable),
color="grey",size=0.3,linetype=1)
# Plot elements that have attributes set outside of aes() will
# not appear on legend!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.