我试图绘制一个图,以条形图显示投资组合中各种证券的回报,然后在条形图上叠加点,表明对这些证券的敞口。然而,我得到的图例完全忽略了这些点,只为条形图绘制了图例。
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))
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)

仅当您在 内部创建美学映射时,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)))
Run Code Online (Sandbox Code Playgroud)
在下面的代码中,我们添加了“虚拟”形状美感,geom_point以便生成形状图例。然后labs我们设置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()
Run Code Online (Sandbox Code Playgroud)