R ggplot2:如何自动调整小节后面的灰色区域

时间:2019-08-19 10:58:56

标签: r ggplot2

我要调整以使灰色区域的宽度和条形图更小。 现在,在该图的左右两侧的灰色区域太多了,如您在我的屏幕快照中所见。寻找一种解决方案,该解决方案还可以捕获图表中我拥有3条或更多条形图的情况。

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")

enter image description here

2 个答案:

答案 0 :(得分:1)

width=.2中删除geom_bar,因为您告诉R使您的条形图仅占据20%的情节。 geom_bar将默认宽度设置为绘图的90%(请参见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")

答案 1 :(得分:1)

James Martherus所说的肯定是解决方案的一部分。但是,由于图总是填充整个图窗口,因此看起来很奇怪。因此,您可以设置绘图边距:

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"))

enter image description here

或者您只是按自己的方式保存它:


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) 

通过这种方式,您可以毫无保留地获得利润。