从ggplot2中的图例中删除空格的方法

时间:2014-12-02 19:44:17

标签: r ggplot2 legend legend-properties

我有一个堆积的条形图,我很高兴,但我正在努力将底部的图例移到靠近图形的地方(那里有很多空白区域)。

这是我的可重复代码:

library(ggplot2)
library(scales)
library(reshape2)
Rdates <- seq(as.Date("2004-02-01"), length=120, by="1 month") - 1
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(120,-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")

postive <- subset(MAINDF,value >= 0)
negative <- subset(MAINDF,value < 0)

gg <- ggplot()
gg <- gg + geom_bar(data = postive , aes(x = dates, y = value, fill = variable),stat="identity")
gg <- gg + geom_bar(data = negative , aes(x = dates, y = value, fill = variable),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 Net Returns") 
gg <- gg + ggtitle("Contribution by Strategy")
gg <- gg + scale_y_continuous(labels = percent_format())
gg <- gg + scale_fill_manual(values=CUSTOMpalette)
gg <- gg + guides(fill=guide_legend(nrow=2,byrow=TRUE))
gg

我尝试使用legend.margin=unit(-2,"mm"),,但它似乎无法正常工作。将此框移近图表的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

尝试玩:

gg <- gg + theme(legend.position = c(0.5, 0.5))

此外,您可能希望在 true 再现性的示例中添加以下内容:

library(ggplot2)
library(reshape2)
library(scales)