我没有找到关于Stack Overflow的问题,所以我允许自己写这个。我想制作有序堆叠条形图(有两个或更多分组/填充变量),所以我编写了代码,你可以在下面找到。
我想知道在没有创建有序因子的情况下更简单/更好地使用ggplot函数是否可行?我会非常感谢所有提示。
这是我的代码
p<-ggplot(data=gf18l, aes(x=variable,y=valuep,fill=ID)) +
geom_bar(position='stack',stat='identity')
varorder<-gf18l[order(gf18l$ID,gf18l$valuep), ]
varorder<-varorder[varorder$ID==1,'variable']
gf18l$variable<-factor(as.character(gf18l$variable),
levels=varorder,
labels=varorder,
ordered=T)
p %+% gf18l + coord_flip()
这是我的数据
gf18l<-structure(list(ID = c("1", "2", "1", "2", "1", "2", "1", "2",
"1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1",
"2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2",
"1", "2", "1", "2"), variable = structure(c(1L, 1L, 2L, 2L, 3L,
3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L,
11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L, 17L,
17L, 18L, 18L, 19L, 19L), .Label = c("GF18A_01", "GF18A_02",
"GF18A_03", "GF18A_04", "GF18A_05", "GF18A_06", "GF18A_07", "GF18A_08", "GF18A_09", "GF18A_10", "GF18A_11", "GF18A_12", "GF18A_13", "GF18A_14",
"GF18A_15", "GF18A_16", "GF18A_17", "GF18A_18", "GF18A_19"), class = "factor"),
value = c(11336L, 1007L, 2691L, 9629L, 7192L, 5136L, 7740L,
4581L, 8794L, 3536L, 7014L, 5317L, 1991L, 10323L, 529L, 11777L,
5685L, 6649L, 5465L, 6869L, 906L, 11406L, 357L, 11964L, 7828L,
4510L, 7809L, 4525L, 6269L, 6061L, 126L, 12186L, 1533L, 10782L,
9719L, 2601L, 989L, 11285L), valuep = c(0.918415296119258,
0.0815847038807421, 0.218425324675325, 0.781574675324675,
0.583387410772226, 0.416612589227774, 0.628195763330898,
0.371804236669102, 0.713219789132198, 0.286780210867802,
0.568810315465088, 0.431189684534912, 0.161685885983434,
0.838314114016567, 0.042987160734601, 0.957012839265399,
0.460921031295606, 0.539078968704394, 0.443084157613102,
0.556915842386898, 0.0735867446393762, 0.926413255360624,
0.0289749208668128, 0.971025079133187, 0.634462635759442,
0.365537364240558, 0.633127939030323, 0.366872060969677,
0.508434712084347, 0.491565287915653, 0.010233918128655,
0.989766081871345, 0.124482338611449, 0.875517661388551,
0.78887987012987, 0.21112012987013, 0.080576829069578, 0.919423170930422
)), .Names = c("ID", "variable", "value", "valuep"), row.names = c(NA,
-38L), class = "data.frame")
答案 0 :(得分:2)
您可以使用limits
scale_x_discrete
函数中的ggplot2
参数来订购条形码。
ggplot(data=gf18l, aes(x=variable,y=valuep,fill=ID)) +
geom_bar(position='stack',stat='identity') +
scale_x_discrete(limits=with(gf18l, variable[ID==1][order(valuep[ID==1])])) +
coord_flip()