我的数据如下:
DF=structure(list(experiment = c("BR", "CH", "EP", "IP", "JU", "MA",
"SA", "ST", "SV", "VI"), duration = c(28L, 9L, 20L, 4L, 14L,
30L, 26L, 23L, 17L, 6L), percentage_total_exp = c(47.2222222222222,
51.063829787234, 52.3809523809524, 79.0322580645161, 48.6842105263158,
72.7272727272727, 62.0689655172414, 34.469696969697, 61.1111111111111,
34.8837209302326), nb_reaction = c(29, 29, 14, 11, 40, 11, 14,
14, 23, 18)), .Names = c("experiment", "duration", "percentage_total_exp",
"nb_reaction"), row.names = c(NA, -10L), class = "data.frame")
我融化了我的数据,以便显示为以下ggplot
meltR=melt(DF)
ggplot(meltR, aes(x=experiment , y = value, group = variable, fill = variable)) + geom_bar(stat = "identity", position="dodge")
现在的问题是,我希望这个版本有3个版本。一个按变量排序:duration
,第二个按变量排序:percentage_total_exp
,最后一个按变量排序:nb_reaction
。
我不知道如何指定。我试过了y = reorder(value, -duration)
,但事实上它并没有认出持续时间。在这种情况下,融化是一个坏主意吗?怎么做?
编辑2:要添加的代码最少,因为我的experiment
名称实际上很长
plots <- lapply(levels(meltR$variable), function(lev) {
meltR$experiment <- factor(meltR$experiment, levels = meltR$experiment[order(meltR$value[meltR$variable == lev])])
ggplot(meltR, aes(x=experiment , y = value, group = variable, fill = variable)) + geom_bar(stat = "identity", position="dodge") + ggtitle(lev) + theme_bw() + theme(axis.text.x = element_text(size=10, angle=45, hjust=1, vjust=1, face="bold"))
})
grid.arrange(grobs = plots)
非常感谢
答案 0 :(得分:1)
duration
不是列名,而是示例中名为variable
的列的因子级别。因此,它不会那样工作。一种选择可以是循环三个因子级别或variable
,根据value
重新排序,然后绘制。以下是它的工作原理:
library(ggplot2)
library(reshape2)
library(gridExtra)
DF=structure(list(experiment = c("BR", "CH", "EP", "IP", "JU", "MA",
"SA", "ST", "SV", "VI"), duration = c(28L, 9L, 20L, 4L, 14L,
30L, 26L, 23L, 17L, 6L), percentage_total_exp = c(47.2222222222222,
51.063829787234, 52.3809523809524, 79.0322580645161, 48.6842105263158,
72.7272727272727, 62.0689655172414, 34.469696969697, 61.1111111111111,
34.8837209302326), nb_reaction = c(29, 29, 14, 11, 40, 11, 14,
14, 23, 18)), .Names = c("experiment", "duration", "percentage_total_exp",
"nb_reaction"), row.names = c(NA, -10L), class = "data.frame")
meltR=melt(DF)
plots <- lapply(levels(meltR$variable), function(lev) {
meltR$experiment <- factor(meltR$experiment, levels = meltR$experiment[order(-meltR$value[meltR$variable == lev])])
ggplot(meltR, aes(x=experiment , y = value, group = variable, fill = variable)) + geom_bar(stat = "identity", position="dodge") + ggtitle(lev)
})
grid.arrange(grobs = plots)