R:ggplot2 - 条形图中的堆叠和躲避

R: ggplot2 - stacking and dodging in bar graphs

使用玩具数据集创建一个简单的条形图,使用 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() 或其他地方无效? (刻面总是带有闪避的条)

您已在审美映射中指定 x=variable,因此变量(即苹果和香蕉)中的每个值沿 x 轴都有自己的位置,没有任何东西可以堆叠。

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

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