簡體   English   中英

ggplot2圖例,用於結合geom_bar和geom_point的繪圖

[英]ggplot2 legend for plot combining geom_bar and geom_point

我正在嘗試繪制一個圖,以條形圖顯示投資組合中各種證券的收益,然后在指示條上疊加指示這些證券敞口的點。 但是,我得到的圖例完全忽略了這些點,只繪制了條形圖例。

產生具有類似結構的數據框:

out<-data.frame(security=c("A", "B", "C", "D", "A", "B", "C", "D"), avg_weight=c(0.1,0.2,0.3,0.4, 0.1, 0.2, 0.3, 0.4), return_type=c(rep("systematic",4), rep("idiosyncratic",4)), return=rnorm(8))

現在,作圖

g <- ggplot(data=out, aes(x=factor(security, levels=out$security), y=return))
g <- g + geom_bar(stat="identity", position="dodge", aes(fill=return_type))
g <- g + geom_point(aes(x=factor(security, levels=out$security), y=avg_weight))
g <- g + ggtitle("Systematic and Idiosyncratic Returns")
g <- g + theme(axis.text.x=element_text(angle=70, hjust=1))
g + xlab("Security Description") + ylab("Return")

繪制結果

如何獲得圖例中的第三個條目,例如:

  • 曝光

ggplot僅當您在aes內創建美學映射時才生成圖例。 通常,這是通過將數據列映射到諸如fillshapecolor類的美學元素來完成的。 在這里,我們實際上並不想將avg_weight映射到美學,因此我們將shape用作“虛擬”美學,只是為了獲得圖例。

首先,為數據可重復性設置種子:

# Set a seed for reproducibility
set.seed(4)
out<-data.frame(security=c("A", "B", "C", "D", "A", "B", "C", "D"), 
                avg_weight=c(0.1,0.2,0.3,0.4, 0.1, 0.2, 0.3, 0.4), 
                return_type=c(rep("systematic",4), rep("idiosyncratic",4)), return=cumsum(rnorm(8,0,0.1)))

在下面的代碼中,我們向geom_point添加了“虛擬”形狀美感,以便生成形狀圖例。 然后在labs我們將shape=NULL設置shape=NULL使形狀圖例沒有標題。

ggplot(data=out, aes(x=security)) + 
  geom_bar(stat="identity", aes(y=return, fill=return_type, group=return_type), position="dodge") +
  geom_point(aes(y=avg_weight, shape="Exposure")) + 
  ggtitle("Systematic and Idiosyncratic Returns") +
  theme(axis.text.x=element_text(angle=70, hjust=1)) +
  labs(x="Security Description", y="Return", shape=NULL) +
  theme_classic()

在此處輸入圖片說明

暫無
暫無

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

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