Rdates <- c("2007-01-31","2007-02-28","2007-03-30","2007-04-30","2007-05-31","2007-06-29","2007-07-31","2007-08-31","2007-09-28","2007-10-31")
Rdates <- as.Date(Rdates)
Cnames <- c("Column 1 Really Long","Column 2 Really Long","Column 3 Really Long","Column 4 Really Long","Column 5 Really Long","Column 6 Really Long","Column 7 Really Long","Column 8 Really Long","Column 9 Really Long","Column 10 Really Long")
MAINDF <- data.frame(replicate(10,runif(10,-0.03,0.03)))
rownames(MAINDF) <- Rdates
colnames(MAINDF) <- Cnames
CUSTOMpalette <- c("#1a2ffa", "#0d177d", "#1a9ffa", "#fa751a", "#4b8e12", "#6fd21b", "#fae51a", "#c3b104", "#f5df05", "#dcc805")
MAINDF[,"dates"] <- Rdates
MAINDF <- melt(MAINDF,id.vars="dates")
gg <- ggplot(MAINDF, aes(x = dates, y = value, fill = variable))
gg <- gg + geom_bar(stat = "identity")
gg <- gg + scale_x_date(breaks = "3 months", labels=date_format("%b%y"),limits=c(min(as.Date(MAINDF$dates)),max(as.Date(MAINDF$dates))))
gg <- gg + theme(
axis.text.x= element_text(color="black",angle=45, size=10, vjust=0.5),
axis.text.y= element_text(color="black", size=12, vjust=0.5),
axis.title.y = element_text(color="black",size=12, vjust=0.5),
plot.title = element_text(color="black",face="bold",size=14, hjust=0.5,vjust=1),
panel.background = element_blank(),
panel.border = element_rect(linetype = "solid", colour = "black",fill=NA),
legend.position="bottom",
legend.title = element_blank(),
legend.key = element_rect(fill="white"), legend.background = element_rect(fill=NA)
)
gg <- gg + xlab("") + ylab("Monthly Returns")
gg <- gg + ggtitle("Contribution by Strategy")
gg <- gg + scale_y_continuous(labels = percent_format())
gg <- gg + scale_fill_manual(values=CUSTOMpalette)
gg
目前有一个ggplot2堆积条形图设置。现在一切正常,除了我有传说的问题。我把它放在底部,但有10个项目,所以有些是截止的(不适合)。我尝试了guides(fill=guide_legend(nrow=2))
,但这会使标签的顺序不同(我希望获得前5个,然后是下面的最后5个。有什么建议吗?
答案 0 :(得分:96)
你真的很亲密。最后尝试一下:
gg+guides(fill=guide_legend(nrow=2,byrow=TRUE))
答案 1 :(得分:15)
以上解决方案仅出于美学目的而提出。在某些情况下,您可能希望将图例包装成行,而不是跨不同美学的列 。对于后代,如下所示。
library(ggplot2)
ggplot(diamonds, aes(x=carat, y=price, col=clarity, shape=cut)) +
geom_point() +
theme(legend.position="bottom")
以下是图例:
要使用行包装图例,我们指定legend.box="vertical"
。下面,我们还减小了紧凑性的余量。
ggplot(diamonds, aes(x=carat, y=price, col=clarity, shape=cut)) +
geom_point() +
theme(legend.position="bottom", legend.box="vertical", legend.margin=margin())