ggplot子组顺序不一致

时间:2018-09-08 17:48:31

标签: r ggplot2

See the plot here

我在ggplot中的一个小细节上遇到了麻烦。如您所见,第一个子组(第8个)在红色条之前具有蓝色条,而其他子组则具有相反的方向……我想不出一种使它们保持一致的方法。有什么想法吗?

这是我的代码:

 library(ggplot2)
 library(reshape2)

grade <- factor(c("8th","10th","12th"), levels = c("8th","10th","12th"))
alc.py <- c("37", "38", "41")
alcpy.st <- c("23", "42", "58" )
alcohol.py <- data.frame(grade, alc.py, alcpy.st)
alcohol.py <- melt(alcohol.py, id.vars = "grade")


ggplot(alcohol.py, aes(x=grade, y=value, fill=variable)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  theme_minimal() +
  xlab("Past Year Alchol Use") +
  ylab("Percentage of use (%)")

1 个答案:

答案 0 :(得分:1)

只需添加另一种审美观,以variable分组即可。

ggplot(alcohol.py, aes(x=grade, y=value, fill=variable, group=variable)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  theme_minimal() +
  xlab("Past Year Alcohol Use") +
  ylab("Percentage of use (%)")

enter image description here