为了账号安全,请及时绑定邮箱和手机立即绑定

创建堆叠的条形图,其中每个堆栈按比例缩放为100%

创建堆叠的条形图,其中每个堆栈按比例缩放为100%

拉风的咖菲猫 2019-08-08 15:12:39
创建堆叠的条形图,其中每个堆栈按比例缩放为100%我有一个像这样的data.frame:df <- read.csv(text = "ONE,TWO,THREE                        23,234,324                        34,534,12                        56,324,124                        34,234,124                        123,534,654")我想生成一个百分比条形图,看起来像这样(在LibreOffice Calc中制作): 因此,条形应该标准化,因此所有堆叠具有相同的高度并且总和为100%。到目前为止,我所能获得的是一个堆积的条形图(不是百分比),使用:barplot(as.matrix(df))有帮助吗?
查看完整描述

3 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

ggplot除了你到目前为止,还有一个使用该软件包(版本3.x)的解决方案。


我们使用set 的position参数。如果要使用(和)的参数,也可以使用。geom_barposition = "fill"position = position_fill()position_fill()vjustreverse


请注意,您的数据采用“宽”格式,但ggplot2要求采用“长”格式。因此,我们首先需要gather数据。


library(ggplot2)

library(dplyr)

library(tidyr)


dat <- read.table(text = "    ONE TWO THREE

1   23  234 324

2   34  534 12

3   56  324 124

4   34  234 124

5   123 534 654",sep = "",header = TRUE)


# Add an id variable for the filled regions and reshape

datm <- dat %>% 

  mutate(ind = factor(row_number()) %>% 

  gather(variable, value, -ind)


ggplot(datm, aes(x = variable, y = value, fill = ind)) + 

    geom_bar(position = "fill",stat = "identity") +

    # or:

    # geom_bar(position = position_fill(), stat = "identity") 

    scale_y_continuous(labels = scales::percent_format())


查看完整回答
反对 回复 2019-08-08
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

克里斯比利是严格的,你只需要列的比例。使用您的数据是:

 your_matrix<-( 
               rbind(
                       c(23,234,324), 
                       c(34,534,12), 
                       c(56,324,124), 
                       c(34,234,124),
                       c(123,534,654)
                    )
                )

 barplot(prop.table(your_matrix, 2) )


查看完整回答
反对 回复 2019-08-08
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

prop.table是获得表格比例的友好方式。

m <- matrix(1:4,2)

 m     [,1] [,2][1,]    1    3[2,]    2    4

保证金空白为您提供整个表格的比例

 prop.table(m, margin=NULL)
     [,1] [,2][1,]  0.1  0.3[2,]  0.2  0.4

给它1给你行比例

 prop.table(m, 1)
      [,1]      [,2][1,] 0.2500000 0.7500000[2,] 0.3333333 0.6666667

2是列比例

 prop.table(m, 2)
          [,1]      [,2][1,] 0.3333333 0.4285714[2,] 0.6666667 0.5714286


查看完整回答
反对 回复 2019-08-08
  • 3 回答
  • 0 关注
  • 766 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信