R 创建堆叠条形图,其中每个堆叠的比例总和为100%

R 创建堆叠条形图,其中每个堆叠的比例总和为100%,r,ggplot2,R,Ggplot2,我有这样一个data.frame: df <- read.csv(text = "ONE,TWO,THREE 23,234,324 34,534,12 56,324,124 34,234,124 123,534,654") 有什么帮助吗 只需将每个元素除以其列中

我有这样一个data.frame:

df <- read.csv(text = "ONE,TWO,THREE
                       23,234,324
                       34,534,12
                       56,324,124
                       34,234,124
                       123,534,654")

有什么帮助吗

只需将每个元素除以其列中的值之和即可

这样做就足够了:

data.perc <- apply(data, 2, function(x){x/sum(x)})

data.percprop.table是一种很好的获取表格比例的友好方式

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4
给它1表示行比例

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
2是列比例

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

这里有一个解决方案,它使用了
ggplot
包(3.x版)以及您目前所获得的功能

我们使用
geom_bar
position
参数设置为
position=“fill”
。如果要使用
position\u fill()
vjust
reverse
)的参数,也可以使用
position=position\u fill()

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

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())
库(ggplot2)
图书馆(dplyr)
图书馆(tidyr)
dat%
聚集(变量,值,-ind)
ggplot(datm,aes(x=变量,y=值,fill=ind))+
几何图形栏(position=“fill”,stat=“identity”)+
#或:
#几何图形栏(位置=位置填充(),stat=“identity”)
比例是连续的(标签=比例::百分比格式()

克里斯·比利是正确的,你只需要按列列出比例。使用您的数据是:

 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) )

你的_矩阵melt()是什么包的一部分?是吗?是的;我道歉。在ggplot2自己加载这些包的这么长时间里,我已经生锈了。我使用重塑包中的melt进行了尝试,我得到了以下错误:“scale$标签中的错误(中断):未使用的参数(中断)”我想知道这是否是因为我正在从csv读取。@JulioDiaz Hmmm。很难说发生了什么,特别是如果您处理的数据与问题中的示例不完全相同。我会确保所有软件包都是最新的,并且您使用的是R 2.14.2(我必须升级到2.14.2才能让ggplot 0.9.0中的一些东西正常工作)。对于2018年之后出现这种情况的人,请将“labels=percent_format()”替换为“scales::percent”。您好,这并没有让我的数据安静下来,
rowSums(data.perc)
不是每行1。相反,我使用的是:
data.perc您有NAs或零求和线吗?否则我不太明白为什么那不起作用……这应该是公认的答案。非常简单且简单。@kboom它不使用操作员标记其问题的
ggplot2