ggplot:position_dodge导致重叠?

时间:2016-05-05 19:42:51

标签: r ggplot2 dplyr

我有以下工作流程:

rm(list=ls())

data(mtcars)
attach(mtcars)

library(ggplot2)
library(plyr)
library(dplyr)
library(scales)
library(reshape2)
library(lazyeval)

my_func <- function(x, y) {
  test<<-mtcars %>% group_by_(x, y) %>%
    summarise(Freq = n()) %>% 
    mutate(Freq = Freq/sum(Freq))
  test
  } 
my_func('gear', 'cyl')

ggplot(test, aes(x=gear, y=Freq))+
  geom_bar(stat="identity", aes(fill=cyl), position=position_dodge(width=0.1))+
  scale_y_continuous(labels=percent_format(), limits = c(0,1))

但是,结果图不会显示彼此相邻的条形图,而是显示彼此之间的条形图。给出了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您需要将cyl列转换为因子。

test$cyl <- as.factor(test$cyl)
ggplot(test, aes(x=gear, y=Freq))+
       geom_bar(stat="identity", aes(fill=cyl), position=position_dodge(width=1))+
       scale_y_continuous(labels=percent_format(), limits = c(0,1))

enter image description here