簡體   English   中英

添加 geom_hline 圖例而不搞砸 geom_line 圖例

[英]add geom_hline legend without screwing up geom_line legend

我正在嘗試繪制一個簡單的(碎石)圖,其中包含一些額外的geom_hlinegeom_vline

問題是:每當我添加show_guide=TRUE添加一些aes()geom_xline ,我都會搞砸原始圖例。

這是一些(丑陋的)假數據:

exdf <- data.frame(rep(x=1:12, times = 3), rep(x = c("A", "B", "C"), times = 6), rnorm(36), stringsAsFactors = FALSE)
colnames(exdf) <- c("PC", "variable", "eigenvalue") 

這是我的情節:

g <- ggplot(data = exdf, mapping = aes(x = factor(PC), y = eigenvalue))
g <- g + geom_line(mapping = aes(group = factor(variable), linetype = variable))
g <- g + geom_vline(xintercept = 7, colour = "green", show_guide = TRUE)

在此處輸入圖片說明在此處輸入圖片說明

如何在不污染其他圖例的情況下為geom_vline添加單獨的圖例?

無法理解為什么一層的顏色會改變另一個圖例的顏色。

這部分解決了問題:

g <- ggplot(data = exdf, mapping = aes(x = factor(PC), y = eigenvalue))
g <- g + geom_line(mapping = aes(group = factor(variable), linetype = variable))
g <- g + geom_vline(aes(xintercept = x, colour = Threshold), data.frame(x = 7, Threshold = "A"), show_guide = TRUE) + scale_colour_manual(values = c(A = "green")

在此處輸入圖片說明

但是圖例的可變部分仍然會有交叉,盡管不是綠色的。

或者,您可以使用帶有兩行的新數據框的 geom_line,兩行的 x 和 y 都等於數據的下限和上限。 這將為您提供一個圖例,其中有一條水平綠線作為您的閾值,而沒有垂直線。

基於@Nick K 在上面的建議,這里有一種方法可以通過不同的data =為不同的層使用干凈的圖例來做到這一點。

    exdf <- data.frame(rep(x=1:12, times = 3), rep(x = c("A", "B", "C"), times = 6), rnorm(36), stringsAsFactors = FALSE)
colnames(exdf) <- c("PC", "variable", "eigenvalue") 
    g <- ggplot()
    g <- g + geom_line(data = exdf, mapping = aes(x = factor(PC), y = eigenvalue, group = factor(variable), linetype = variable))
    g
    thresholds <- data.frame(threshold = "Threshold-A", PC = 7, ymin = min(exdf$eigenvalue), ymax = max(exdf$eigenvalue))
    g <- g + geom_linerange(data = thresholds, mapping = aes(x = PC, ymin = ymin, ymax = ymax, color = threshold))
    g

產量:

清潔傳奇

注意:

  • 我知道,原始數據exdf是愚蠢的,並且繪制了丑陋的情節; 這不是重點。
  • 請注意,您必須為兩個圖層設置data =參數,並將第一個g <- ggplot()保留為空白,否則 ggplot2 會對數據框感到困惑。
  • 是的,這是一個 hack 工作(見下文),而且它也不會像geom_vline那樣填充繪圖的 y 高度。

作為附加組件(不是解決方案! ),以下是它應該如何與geom_vline一起geom_vline

exdf <- data.frame(rep(x=1:12, times = 3), rep(x = c("A", "B", "C"), times = 6), rnorm(36), stringsAsFactors = FALSE)
colnames(exdf) <- c("PC", "variable", "eigenvalue") 
g <- ggplot()
g <- g + geom_line(data = exdf, mapping = aes(x = factor(PC), y = eigenvalue, group = factor(variable), linetype = variable))
g
g + geom_vline(data = thresholds, mapping = aes(xintercept = PC, color = threshold), show_guide = TRUE)

產量:

通過 geom_vline 的凌亂圖例

填充使yHeight,正如你所期望從geom_vline ,但不知何故,打亂了傳說中variable (注意垂直線)。

不知道為什么會這樣,對我來說感覺就像一個錯誤。 這里報道: https : //github.com/hadley/ggplot2/issues/1267

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM