如何在ggplot中更改绘图区域的大小?

时间:2016-03-16 21:51:18

标签: r ggplot2 gridextra

我有两个图,需要并排绘制。我希望情节区域保持一致。我有以下代码(注意这只是一个例子来说明问题):

dat1 <- theData[theData$WP >= 0 & theData$Asset.Class == "Equity" & !is.na(theData$PBGroup),]
dat2 <- theData[theData$WP < 0 & theData$Asset.Class == "Equity" & !is.na(theData$PBGroup),]
theSums <- aggregate(theData$WPPercent[theData$Asset.Class == "Equity"], by = list(theData$PBGroup[theData$Asset.Class == "Equity"]), sum)
thePlot1 <- ggplot(data = dat1, aes(x=PBGroup, y=WPPercent)) + 
  ggtitle("Value Exposure (Price to Book)") +
  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
  theme(plot.title = element_text(vjust=1.5, face="bold", size = 20), 
        axis.title.x = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, size = 7), 
        axis.title.y = element_blank()) + scale_y_continuous(labels = percent) + 
  geom_bar(stat = "identity", fill = "darkgreen") +
  geom_bar(data = dat2, aes(x=PBGroup, y=WPPercent),stat = "identity", fill = "darkred") +
  geom_text(data = data.frame(x = theSums$Group.1, y = sign(theSums$x)*.0175), aes(label = paste0(100*round(theSums$x,3), '%'), x = theSums$Group.1, y = sign(theSums$x)*.0175), size = 8)


dat3 <- theData[theData$WP >= 0 & theData$Asset.Class == "Equity" & !is.na(theData$MCGroup),]
dat4 <- theData[theData$WP < 0 & theData$Asset.Class == "Equity" & !is.na(theData$MCGroup),]
theSums2 <- aggregate(theData$WPPercent[theData$Asset.Class == "Equity"], by = list(theData$MCGroup[theData$Asset.Class == "Equity"]), sum)
thePlot2 <- ggplot(data = dat3, aes(x=MCGroup, y=WPPercent)) + 
  ggtitle("Market Cap Exposure (Billions)") + 
  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
  theme(plot.title = element_text(vjust=1.5, face="bold", size = 20), 
        axis.title.x = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, size = 7),
        axis.title.y = element_blank()) + scale_y_continuous(labels = percent) +  
  geom_bar(stat = "identity", fill = "darkgreen") +
  geom_bar(data = dat4, aes(x=MCGroup, y=WPPercent),stat = "identity", fill = "darkred") +
  geom_text(data = data.frame(x = theSums2$Group.1, y = sign(theSums2$x)*.0175), aes(label = paste0(100*round(theSums2$x,3), '%'), x = theSums2$Group.1, y = sign(theSums2$x)*.0175), size = 8)

grid.arrange(thePlot1, thePlot2, ncol=2)

这会产生以下结果:

enter image description here

请注意,两幅图的绘图区域大小不同,其中一幅略高于另一幅图。

0 个答案:

没有答案