简体   繁体   中英

R ggplot2: how to automatically adjust the grey area behind the barplot

I want to adjust make the width of the gray area and the bar plot smaller. Now the grey area on the left and right to the plot is too much as you can see in my screenshot. Looking for a solution that also captures the scenario that I have 3 or more bars in the chart.

ggplot(data=MyDataFrame, aes(x='Text', y=MetricColumn, fill=LegendTag))+ 
  scale_fill_brewer(palette="Set3")+ 
  geom_bar(stat="identity", width=0.2)+
  geom_text(aes(label=paste0(MetricColumn,"%")), position = position_stack(vjust = .5), size = 3.5, color = "black")+
  labs(title="Text of the title")+ 
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  theme(legend.position="left")

在此处输入图片说明

Remove the width=.2 from geom_bar as you're telling R to make your bar take up only 20% of the plot. geom_bar sets the default width at 90% of the plot (see the documentation ).

ggplot(data=MyDataFrame, aes(x='Text', y=MetricColumn, fill=LegendTag))+ 
  scale_fill_brewer(palette="Set3")+ 
  geom_bar(stat="identity")+
  geom_text(aes(label=paste0(MetricColumn,"%")), position = position_stack(vjust = .5), size = 3.5, color = "black")+
  labs(title="Text of the title")+ 
  theme(plot.title = element_text(hjust = 0.5, face="bold"))+
  theme(legend.position="left")

What James Martherus says is definitly part of the solution. But since a plot always fills out the whole plotting window it will look weird. So youc an either set the plot margins:

ggplot(data=diamonds, aes(x= "Text", y= ..count../sum(..count..), fill = cut,
                          label = scales::percent(..count../sum(..count..)))) + 
  scale_fill_brewer(palette="Set3")+ 
  geom_bar(stat="count", show.legend = F) +
  geom_text(stat = 'count', position = position_stack(vjust = .5), size = 3, color = "black") +
  labs(x = NULL) +
  scale_y_continuous(labels = scales::percent, name = "Percent") +
  theme(plot.margin = unit(c(0.5,7, 0.5, 7), "cm"))

在此处输入图片说明

Or you just save it the way you want it to be:


p <- ggplot(data=diamonds, aes(x= "Text", y= ..count../sum(..count..), fill = cut,
                          label = scales::percent(..count../sum(..count..)))) + 
  scale_fill_brewer(palette="Set3")+ 
  geom_bar(stat="count", show.legend = F) +
  geom_text(stat = 'count', position = position_stack(vjust = .5), size = 6, color = "black") +
  labs(x = NULL) +
  scale_y_continuous(labels = scales::percent, name = "Percent") +
  theme(axis.title.y = element_text(size = 20),
        axis.text = element_text(size = 15))


ggsave("D:/R/plot.png", width = 5, height = 15, dpi = 200) 

This way you get it without the margins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM