ggplot2中堆叠图的控制顺序

时间:2017-02-22 05:11:38

标签: r ggplot2

我的数据结构类似于以下示例:

Quarter <- c("Q1", "Q2", "Q2", "Q3", "Q4")
Weather <- c("cloudy", "cloudy", "sunny", "sunny", "cloudy")
Duration <- c(16, 10, 12, 15, 14)
WeatherCondData <- data.frame(Quarter, Weather, Duration)

当我绘制这些数据时,第二季度的第二个条目(Q2)是晴天,但是在图中没有按顺序显示 - 多云是第二个条目。

ggplot(WeatherCondData, aes(x = Quarter, y = Duration, fill = Weather)) +
  geom_bar(stat = "identity", position = "stack") +
  theme_classic()

如何更改绘图,以便阳光是Q2堆叠条的顶部?

感谢。

1 个答案:

答案 0 :(得分:3)

使用stringsAsFactors = Fdata.frame()中停用自动因子转换功能。然后使用factor()levels args设置顺序。

WeatherCondData <- data.frame(Quarter, Weather, Duration, stringsAsFactors = F)
WeatherCondData$Weather <- factor(WeatherCondData$Weather, levels=c('sunny','cloudy'))

enter image description here