![](/img/trans.png)
[英]How to get a common legend for stacked geom_bar and geom_point in ggplot2?
[英]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
內創建美學映射時才生成圖例。 通常,這是通過將數據列映射到諸如fill
, shape
或color
類的美學元素來完成的。 在這里,我們實際上並不想將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.