Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在不保留标签顺序的情况下在打印中堆叠条_R_Ggplot2 - Fatal编程技术网

R 在不保留标签顺序的情况下在打印中堆叠条

R 在不保留标签顺序的情况下在打印中堆叠条,r,ggplot2,R,Ggplot2,ggplot根据标签保留堆叠钢筋的顺序: d <- read.table(text='Day Location Length Amount 1 2 3 1 1 1 4 2 3 3 3 2 3 2 5 1',header=T) d$Amount<-as.factor(d$Amount) # in real world is not numeric ggplot(d, aes(x = Da

ggplot根据标签保留堆叠钢筋的顺序:

d <- read.table(text='Day Location Length Amount
            1 2 3 1
            1 1 4 2
            3 3 3 2
            3 2 5 1',header=T)

d$Amount<-as.factor(d$Amount) # in real world is not numeric

ggplot(d, aes(x = Day, y = Length)) + 
  geom_bar(aes(fill = Amount), stat = "identity")

d我想出了这个解决方案:

(1) 首先,按值的列降序对data.frame进行排序

(2) 然后复制一列值,作为因子

(3) 按新因子(值)在ggplot组中

d
d <- read.table(text='Day Length Amount
                1 3 1
                1 4 2
                3 3 2
                3 5 1',header=T)

d$Amount<-as.factor(d$Amount) 

d <- d[order(d$Length, decreasing = TRUE),] # (1)

d$LengthFactor<-factor(d$Length, levels= unique(d$Length) ) # (2)

ggplot(d)+
  geom_bar(aes(x=Day, y=Length, group=LengthFactor, fill=Amount), # (3)
           stat="identity", color="white") 
{
library(data.table)
sam<-data.frame(population=c(rep("PRO",8),rep("SOM",4)),
                allele=c("alele1","alele2","alele3","alele4",rep("alele5",2),
                            rep("alele3",2),"alele2","alele3","alele3","alele2"), 
                frequency=rep(c(10,5,4,6,7,16),2) #,rep(1,6)))
)

sam <- setDT(sam)[, .(frequencySum=sum(frequency)), by=.(population,allele)]

sam <- sam[order(sam$frequency, decreasing = TRUE),] # (1)

# (2)
sam$frequency<-factor(sam$frequency, levels = unique(sam$frequency) )

library(ggplot2)
ggplot(sam)+
  geom_bar(aes(x=population, y=frequencySum, group=frequency, fill=allele), # (3)
           stat="identity", color="white") 
}