R 在不保留标签顺序的情况下在打印中堆叠条
ggplot根据标签保留堆叠钢筋的顺序: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
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")
}