【问题标题】:Inconsistent ggplot subgroup orderggplot子组顺序不一致
【发布时间】:2018-09-08 17:48:31
【问题描述】:

我在 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 (%)")

【问题讨论】:

  • 您的代码不可重现。请修复您的代码。
  • 对,你需要先加载包
  • 仍然无法重现。我收到此错误消息:Error in data.frame(grade, alc.py, alcpy.st) : object 'grade' not found.
  • 糟糕,忘记了一行。现在应该没事了
  • 只需添加另一种美学,ggplot(alcohol.py, aes(x=grade, y=value, fill=variable, group=variable))groupvariable

标签: r ggplot2


【解决方案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 (%)")

【讨论】:

  • 太棒了,非常感谢!
猜你喜欢
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
相关资源
最近更新 更多