【问题标题】:Stack plot in R with large datasetR中的堆栈图与大型数据集
【发布时间】:2019-10-19 15:39:24
【问题描述】:

我有一个相对较大的数据集,我正在尝试将其绘制到 R 中。这就是我的数据集的 sn-p 的样子

> dat
    Who      Activity Duration
1    Ch    Stationary       14
2    Ch    Stationary       18
3    Ch   Interaction        2
4    Ch    Stationary        6
5    Ch   Interaction        1
6    Ch       Display       10
7    Ch   Interaction        6
8    Ch    Stationary        5
9    Ch    Stationary       20
10   Ch    Stationary       13
11   Ch    Stationary       17
12   Co   Interaction        3
13   Co    Stationary       31
14   J    Stationary        8
15   R           OOS        1
16   R   Interaction        1
17   J           OOS        4

我正在尝试使用持续时间作为百分比来构建堆积条形图,而不仅仅是原始值。到目前为止,这是我想出的:

p7 <- ggplot() + 
  geom_bar(aes(y= dat$Duration, x= dat$Who, fill = dat$Activity), 
           stat ="identity")
p7 <- p7 + scale_fill_brewer(palette="Set3")
p7 <- p7 + xlab("Chimp ID") + ylab ("Total Time Spent (min)")
p7 <- p7 + labs(fill = "Behaviour")
p7 + theme_classic()
p7 #Palette graph with percentage values
p7 + 
  geom_bar(position = "fill", stat="identity") + 
  scale_y_continuous(labels = scales::percent_format())

但是,这仍然不会将条形图的总和返回为 100%。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    嗨,索菲亚,

    问题是scales::percent_format()only 格式化带有百分号的数字。您需要自己计算百分比。

    下面的代码会为你计算。

    library(tidyverse)
    
    dat <-  read.delim(text="id,Who,Activity,Duration
    1,Ch,Stationary,14
    2,Ch,Stationary,18
    3,Ch,Interaction,2
    4,Ch,Stationary,6
    5,Ch,Interaction,1
    6,Ch,Display,10
    7,Ch,Interaction,6
    8,Ch,Stationary,5
    9,Ch,Stationary,20
    10,Ch,Stationary,13
    11,Ch,Stationary,17
    12,Co,Interaction,3
    13,Co,Stationary,31
    14,J,Stationary,8
    15,R,OOS,1
    16,R,Interaction,1
    17,J,OOS,4", sep=",")
    
    dat <- dat%>%
      group_by(Who)%>%
      mutate(percent = Duration/sum(Duration))
    
    p7 <- ggplot() + 
      geom_bar(aes(y= dat$percent, x= dat$Who, fill = dat$Activity), 
               stat ="identity")
    p7 <- p7 + scale_fill_brewer(palette="Set3")
    p7 <- p7 + xlab("Chimp ID") + ylab ("Total Time Spent (min)")
    p7 <- p7 + labs(fill = "Behaviour")
    p7 + theme_classic()
    p7 #Palette graph with percentage values
    p7 + 
      geom_bar(position = "fill", stat="identity") + 
      scale_y_continuous(labels = scales::percent_format())
    

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 2012-06-26
      • 1970-01-01
      • 2018-01-29
      • 2011-09-06
      • 2020-07-27
      • 2023-04-10
      • 1970-01-01
      • 2014-06-23
      相关资源
      最近更新 更多