在下图所示的图中,我试图改变y轴上标签的顺序(coord_flip()之前的x轴)。 我希望1在顶部,16在底部。
levels <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
library(ggplot2)
ggplot(all_Q, aes(x=qid, y=correct_per, fill=group), group=qid) +
geom_bar(stat="identity", position=position_dodge()) +
scale_x_discrete(name = "Questions", limits = levels) +
scale_y_continuous(name = "Percent correct") +
coord_flip()
这是我到目前为止所尝试的内容:
levels <- c(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
- &gt;没有变化。
limits = rev(levels)
- &gt;没有变化
limits = rev(levels(levels))
- &gt;来自this question/answer img下面的建议
带有问题子集的可重复示例(8,9,10,11)
dput() output:
structure(list(group = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"), correct_per = c(90.4761904761905, 100, 100, 87.5, 83.3333333333333, 90.9090909090909, 84.6153846153846, 87.5, 80.9523809523809, 88.6363636363636, 100, 70.8333333333333, 63.4146341463415, 76.7441860465116, 76.9230769230769, 62.5), nr_correct = c(38L, 44L, 26L, 21L, 35L, 40L, 22L, 21L, 34L, 39L, 26L, 17L, 26L, 33L, 20L, 15L), nr_incorrect = c(4L, 0L, 0L, 3L, 7L, 4L, 4L, 3L, 8L, 5L, 0L, 7L, 15L, 10L, 6L, 9L), length = c(42L, 44L, 26L, 24L, 42L, 44L, 26L, 24L, 42L, 44L, 26L, 24L, 41L, 43L, 26L, 24L), qid = c("8", "8", "8", "8", "9", "9", "9", "9", "10", "10", "10", "10", "11", "11", "11", "11")), .Names = c("group", "correct_per", "nr_correct", "nr_incorrect", "length", "qid"), row.names = c(NA, -16L), class = c("tbl_df", "tbl", "data.frame"))
save to file
all_Q <- dget(filename)
levels <- c(8,9,10,11)
ggplot(all_Q, aes(x=qid, y=correct_per, fill=group), group=qid) +
geom_bar(stat="identity", position=position_dodge()) +
scale_x_discrete(name = "Questions", limits = levels) +
scale_y_continuous(name = "Percent correct") +
coord_flip()
答案 0 :(得分:1)
最好按特定顺序处理因素。我确定你想要的是
all_Q$qid <- factor(all_Q$qid, levels = c(11, 10, 9, 8))
ggplot(all_Q, aes(x=qid, y=correct_per, fill=group), group=qid) +
geom_bar(stat="identity", position=position_dodge()) +
scale_x_discrete(name = "Questions") +
scale_y_continuous(name = "Percent correct") +
coord_flip()
<强>收率:强>
all_Q$qid <- factor(all_Q$qid, levels = c(11, 10, 9, 8))
<强>收率:强>
答案 1 :(得分:1)
列all_Q$qid
是因子,因此您可以指定传递非数字向量的限制(顺序)。
library(ggplot2)
# Don't use group as you're already grouping by fill
ggplot(all_Q, aes(qid, correct_per, fill = group)) +
geom_bar(stat = "identity", position = "dodge") +
# Passing character vector from 16 to 1
scale_x_discrete(limits = as.character(16:1)) +
# Don't use function scale_y_* only for naming
# With function labs you can specify all the names
labs(x = "Questions",
y = "Correct, %",
fill = "My fill") +
coord_flip()