首页 文章

在分类变量图表中显示%而不是计数

提问于
浏览
141

我正在绘制一个分类变量,而不是显示每个类别值的计数 .

我正在寻找一种方法让 ggplot 显示该类别中值的百分比 . 当然,有可能用计算的百分比创建另一个变量并绘制一个变量,但我必须做几十次,我希望在一个命令中实现它 .

我正在尝试类似的东西

qplot(mydataf) +
  stat_bin(aes(n = nrow(mydataf), y = ..count../n)) +
  scale_y_continuous(formatter = "percent")

但我必须错误地使用它,因为我遇到了错误 .

要轻松重现设置,这是一个简化的示例:

mydata <- c ("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc");
mydataf <- factor(mydata);
qplot (mydataf); #this shows the count, I'm looking to see % displayed.

在实际情况中,我可能会使用 ggplot 而不是 qplot ,但使用stat_bin的正确方法仍然无法实现 .

我也试过这四种方法:

ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent');

ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent') + geom_bar();

ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent');

ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent') + geom_bar();

但所有4给出:

错误:ggplot2不知道如何处理类因子的数据

对于简单的情况,会出现相同的错误

ggplot (data=mydataf, aes(levels(mydataf))) +
  geom_bar()

所以很明显 ggplot 如何与单个载体相互作用 . 我正在挠头,谷歌搜索该错误给了一个result .

9 回答

  • 6

    由于回答了这一问题,因此对 ggplot 语法进行了一些有意义的更改 . 总结上述评论中的讨论:

    require(ggplot2)
     require(scales)
    
     p <- ggplot(mydataf, aes(x = foo)) +  
            geom_bar(aes(y = (..count..)/sum(..count..))) + 
            ## version 3.0.0
            scale_y_continuous(labels=percent)
    

    这是一个使用 mtcars 的可重现示例:

    ggplot(mtcars, aes(x = factor(hp))) +  
            geom_bar(aes(y = (..count..)/sum(..count..))) + 
            scale_y_continuous(labels = percent) ## version 3.0.0
    

    enter image description here

    这个问题目前是谷歌搜索'ggplot count vs百分比直方图'的第一名,所以希望这有助于提取当前所有关于已接受答案的评论中的信息 .

    Remark: 如果 hp 未设置为因子,ggplot将返回:

    enter image description here

  • 54

    这个修改过的代码应该可行

    p = ggplot(mydataf, aes(x = foo)) + 
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        scale_y_continuous(formatter = 'percent')
    

    如果您的数据有NA并且您不希望它们包含在图中,请将na.omit(mydataf)作为参数传递给ggplot .

    希望这可以帮助 .

  • 42

    使用ggplot2 2.1.0版本

    + scale_y_continuous(labels = scales::percent)
    
  • 6

    截至2017年3月, ggplot2 2.2.1我认为最佳解决方案在Hadley Wickham的R for data science book中有所解释:

    ggplot(mydataf) + stat_count(mapping = aes(x=foo, y=..prop.., group=1))
    

    stat_count 计算两个变量:默认情况下使用 count ,但您可以选择使用显示比例的 prop .

  • 17

    如果您想要y轴上的百分比并在条形图上标记:

    library(ggplot2)
    library(scales)
    ggplot(mtcars, aes(x = as.factor(am))) +
      geom_bar(aes(y = (..count..)/sum(..count..))) +
      geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
      scale_y_continuous(labels = percent) +
      labs(title = "Manual vs. Automatic Frequency", y = "Percent", x = "Automatic Transmission")
    

    enter image description here

    添加条形标签时,您可能希望省略y轴以获得更清晰的图表,方法是添加到结尾:

    theme(
            axis.text.y=element_blank(), axis.ticks=element_blank(),
            axis.title.y=element_blank()
      )
    

    enter image description here

  • 28

    如果你想要百分比标签,但在y轴上需要实际的Ns,试试这个:

    library(scales)
    perbar=function(xx){
          q=ggplot(data=data.frame(xx),aes(x=xx))+
          geom_bar(aes(y = (..count..)),fill="orange")
           q=q+    geom_text(aes(y = (..count..),label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="darkgreen") 
          q
        }
        perbar(mtcars$disp)
    
  • 3

    这是分面数据的解决方法 . (@Andrew接受的答案在这种情况下不起作用 . )想法是使用dplyr计算百分比值,然后使用geom_col创建绘图 .

    library(ggplot2)
    library(scales)
    library(magrittr)
    library(dplyr)
    
    binwidth <- 30
    
    mtcars.stats <- mtcars %>%
      group_by(cyl) %>%
      mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
                   labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
             n = n()) %>%
      group_by(cyl, bin) %>%
      summarise(p = n()/n[1]) %>%
      ungroup() %>%
      mutate(bin = as.numeric(as.character(bin)))
    
    ggplot(mtcars.stats, aes(x = bin, y= p)) +  
      geom_col() + 
      scale_y_continuous(labels = percent) +
      facet_grid(cyl~.)
    

    这是情节:

    enter image description here

  • 196

    对于那些在2018年之后到达的人,将“labels = percent_format()”替换为“scales :: percent”

  • 0

    请注意,如果您的变量是连续的,则必须使用geom_histogram(),因为该函数会将变量分组为“bins” .

    df <- data.frame(V1 = rnorm(100))
    
    ggplot(df, aes(x = V1)) +  
      geom_histogram(aes(y = (..count..)/sum(..count..))) 
    
    # if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
    # different category. In this case this does not make sense, as the variable is 
    # really continuous. With the hp variable of the mtcars (see previous answer), it 
    # worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
    # can want to see each value of this variable, and not to group it in bins.
    ggplot(df, aes(x = factor(V1))) +  
      geom_bar(aes(y = (..count..)/sum(..count..)))
    

相关问题