ggplot的堆积条形图

测试名123

我正在尝试使用以下数据框制作堆积的条形图:

 totalleft
        1S 2S 3S 4S 12S 25S      tests
A-000   5  0 10 10   0  NA       A-000
A-001  10  8 10 NA  NA  NA       A-001
A-002   5  3 10 10  10  NA       A-002
A-003   2  0 10  9   0  10       A-003
A-004   5  4 10 10  10  NA       A-004
A-005   5  3 10 10  10  NA       A-005
A-006   8  7 NA 10  10  NA       A-006
A-009   9 10 NA NA  10  10       A-009
A-015  NA  1 NA NA  NA  NA       A-015
A-016  NA  0 10 NA   6   9       A-016
A-017  NA  0 NA NA   4  NA       A-017
A-020  NA  1 NA NA  NA  NA       A-020
A-025  NA  0 NA NA   0  NA       A-025
A-025a NA  0 NA NA  10  NA      A-025a
A-026  NA  9 10 NA   9   9       A-026
A-027  NA  0 10 NA   2   9       A-027
A-028  NA  0 NA NA   1  NA       A-028
A-030  NA  7 NA NA   8   8       A-030
B-000     0  0  7  8   0   0     B-000
B-056     4  0  9 NA   0   5     B-056
B-076     9  9 NA NA  10  10     B-076
B-099     6  5 10 NA   5   9     B-099
B-102     7  0 NA NA   0  10     B-102
B-105    NA  6 NA NA  NA   6     B-105
B-119     7  8 10 10  NA  NA     B-119

但是,大多数文档都涉及针对两个因素的绘图:一个用于沿X轴拆分条形,另一个用于划分每个条形。我的问题是如何通过因子检验将X轴分割,然后将每个条除以相应的行(即1S,2S,3S,4S,12,25S)。

因此,第一个色条将是的色条A-000,其20%将是一种颜色(对于1S,5 /(5 + 10 + 10)),第二个40%将是另一种颜色(3S,10 /(5 + 10 + 10)),最后40%将是另一种颜色(4S,10 /(5 + 10 + 10))

我正在使用此命令作为参考:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()

来自此网站:http : //docs.ggplot2.org/0.9.3.1/geom_bar.html#

信息矿工

因此,您需要重塑数据。您需要一个堆叠的条形图,因此您需要告诉ggplot有关变量1S,2S ...和测试的信息。

#let's melt the data
#library(reshape2)
data.plot.m <-melt(data.plot, id.vars = "tests") #I stored your data in data.plot
data.plot.m$variable <-gsub("X","",data.plot.m$variable) 
#as R doesn't like variable names beginning with numbers,
#it adds an 'X' automatically when
#we load the data with read.table so we remove this from melted data

#now we plot the data
ggplot(data.plot.m,aes(y = value,x = variable,fill = tests)) +
geom_bar(stat = "identity")

在此处输入图片说明您会注意到情节的顺序是不同的。我们将需要重新排序您的变量:

data.plot.m$variable <- factor(data.plot.m$variable, levels = unique(data.plot.m$variable))
#now plot again
ggplot(data.plot.m,aes(y = value,x = variable,fill = tests))+
geom_bar(stat = "identity") 

在此处输入图片说明

我才意识到你想要这个

ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity")

并旋转x轴刻度标签

ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=90))

在此处输入图片说明 注意我如何切换x并填充

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章