【问题标题】:R: ggplot2 - stacking and dodging in bar graphsR:ggplot2 - 条形图中的堆叠和闪避
【发布时间】:2017-09-18 23:29:28
【问题描述】:

使用玩具数据集使用ggplot2 包创建一个带有分面的简单条形图:

library(ggplot2) 
library(reshape2) # to convert to long format 

databas<-read.csv(data=
                    "continent,apples,bananas
                  North America,30,20
                  South America,15,34.5
                  Europe,15,19
                  Africa,5,35")

databaslong<-melt(databas) 

# plotting as colored bars 
ggplot(databaslong, aes(x=variable, y=value, fill=variable))+
  geom_col()+
  facet_grid(.~continent)

并获得以下信息:

如何将苹果放在香蕉上(反之亦然)?为什么指令position="stack"(或position="dodge")在geom_col() 或其他地方不起作用? (刻面总是带有躲避的条)

【问题讨论】:

    标签: r ggplot2 bar-chart facet


    【解决方案1】:

    您已在美学映射中指定x=variable,因此变量中的每个值(即苹果和香蕉)沿 x 轴都有自己的位置,并且没有可堆叠的内容。

    如果您希望为每个大陆堆叠苹果和香蕉,您可以指定 x=continent 代替:

    ggplot(databaslong, 
           aes(x = continent, y = value, fill = variable)) +
      geom_col()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 2012-09-24
      • 2016-04-26
      • 2023-01-21
      相关资源
      最近更新 更多