簡體   English   中英

ggplot:結合圖條/線的圖例?

[英]ggplot: legend for a plot the combines bars / lines?

我想在同一面板上繪制一個經驗PDF + CDF組合。 distro.df pdfcdfday 我希望將pdf值繪制為條形,將cdf繪制為線形。 這是制作情節的技巧:

p <- ggplot(distro.df, aes(x=day))
p <- p + geom_bar(aes(y=pdf/max(pdf)), stat="identity", width=0.95, fill=fillCol)
p <- p + geom_line(aes(y=cdf))
p <- p + xlab("Day") + ylab("")
p <- p + theme_bw() + theme_update(panel.background = element_blank(), panel.border=element_blank())

但是,我很難讓圖例出現。 我想要CDF的一行和pdf的填充塊。 我已經嘗試過使用指南進行各種扭曲,但是似乎什么也沒出現。

建議?

編輯:

根據distro.df的要求:制作合適的distro.df對象:

df <- data.frame(day=0:10)
df$pdf <- runif(length(df$day))
df$pdf <- df$pdf / sum(df$pdf)
df$cdf <- cumsum(df$pdf)

然后在上面進行繪制,然后調用p來查看繪制。

這通常涉及移動fillaes和在二者使用它geom_bargeom_line層。 在這種情況下,您還需要將show_guide = TRUE添加到geom_line

一旦有了,只需在scale_fill_manual設置fill顏色, scale_fill_manual使CDF沒有填充顏色,並使用override.aes對行執行相同的操作。 我不知道您的填充顏色是什么,所以我只用了紅色。

ggplot(df, aes(x=day)) +
    geom_bar(aes(y=pdf/max(pdf), fill = "PDF"), stat="identity", width=0.95) + 
    geom_line(aes(y=cdf, fill = "CDF"), show_guide = TRUE) + 
    xlab("Day") + ylab("") + 
    theme_bw() + 
    theme_update(panel.background = element_blank(), 
               panel.border=element_blank()) +
    scale_fill_manual(values = c(NA, "red"), 
                   breaks = c("PDF", "CDF"), 
                   name = element_blank(), 
                   guide = guide_legend(override.aes = list(linetype = c(0,1))))

我仍然想要上述解決方案(並將檢出@aosmith的答案),但是我目前正在采用一種稍微不同的方法來消除解決問題的需要:

  p <- ggplot(distro.df, aes(x=days, color=pdf, fill=pdf))
  p <- p + geom_bar(aes(y=pdf/max(pdf)), stat="identity", width=0.95)
  p <- p + geom_line(aes(y=cdf), color="black")
  p <- p + xlab("Day") + ylab("CDF")
  p <- p + theme_bw() + theme_update(panel.background = element_blank(), panel.border=element_blank())
  p

這還具有顯示一些先前丟失的信息(即PDF值)的優勢。

暫無
暫無

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

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