【问题标题】:R ggplot2: how to automatically adjust the grey area behind the barplotR ggplot2:如何自动调整条形图后面的灰色区域
【发布时间】:2019-08-19 10:58:56
【问题描述】:

我想调整使灰色区域和条形图的宽度更小。 现在,您可以在我的屏幕截图中看到,绘图左右两侧的灰色区域太多了。正在寻找一种解决方案,该解决方案还可以捕获图表中有 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")

【问题讨论】:

    标签: r ggplot2


    【解决方案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"))
    
    

    或者你只是按照你想要的方式保存它:

    
    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) 
    
    

    这样你得到它没有边距。

    【讨论】:

      【解决方案2】:

      geom_bar 中删除width=.2,因为你告诉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")
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-27
        • 2014-06-29
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-24
        • 2011-07-21
        相关资源
        最近更新 更多