【发布时间】:2017-08-04 09:09:13
【问题描述】:
我正在尝试为五个不同的组绘制两种不同类型的生产。我可以生成绘图并且它看起来已经不错了,尽管最终 ggplot 中的排序不是我想要的那样。
我找到了arrange() 的解决方案,但是尽管这一步中的排序是正确的,但最终的结果又是不同的。
我希望对每个组(1、2、3、4、NA)进行分组,这两种不同类型的生产是相互重叠的。
library(zoo)
library(data.table)
library(ggplot2)
library(dplyr)
DT <- structure(list(Year.Quarter = structure(c(2015, 2015, 2015, 2015,
2015, 2015.25, 2015.25, 2015.25, 2015.25, 2015.25, 2015.5, 2015.5,
2015.5, 2015.5, 2015.5, 2015.75, 2015.75, 2015.75, 2015.75, 2015.75,
2016, 2016, 2016, 2016, 2016, 2016.25, 2016.25, 2016.25, 2016.25,
2016.25), class = "yearqtr")
, Group = c(2L, 1L, 4L, 3L, NA, 2L,
1L, 4L, 3L, NA, 2L, 1L, 4L, 3L, NA, 2L, 1L, 4L, 3L, NA, 2L, 1L,
4L, 3L, NA, 2L, 1L, 4L, 3L, NA)
, Conventional.Prod = c(11.78, 7.31, 7.34, 9.44, 28.72, 11.32, 5.27, 7.47, 8.08, 27.14, 11.49,
4.65, 7.63, 7.07, 25.93, 10.69, 3.68, 6.96, 6.72, 18.31, 9.28,
3.69, 6.86, 6.34, 19.14, 9.25, 3.69, 6.9, 6.16, 17.7)
, Unconventional.Prod = c(15.22, 10.69, 7.66, 15.56, 30.28, 15.68, 10.73, 7.53, 15.92, 29.86,
13.51, 10.35, 7.37, 15.93, 28.07, 13.31, 10.32, 7.04, 16.28,
25.69, 12.72, 9.31, 7.14, 16.66, 25.86, 12.75, 9.31, 7.1, 16.84, 24.3))
, .Names = c("Year.Quarter", "Group", "Conventional.Prod", "Unconventional.Prod"), row.names = c(NA, -30L), class = c("data.table",
"data.frame"))
data.table::melt(DT,
, id.vars = c("Year.Quarter", "Group")
, measure.vars = c("Conventional.Prod", "Unconventional.Prod")
) %>% arrange(Year.Quarter, Group, variable) %>% ggplot(data = ., aes(x = Year.Quarter, y = value, color = variable, fill = as.factor(Group))) +
geom_area(stat = "identity", position = "fill") +
#geom_line(aes(x = Calendar.Data.Year.and.Quarter ,y = value)) +
theme(legend.title=element_blank()) +
scale_x_yearqtr(format = "%Y-Q%q",n = 8, expand = c(0,0))
arrange 步骤之后的排序符合预期:
Year.Quarter Group variable value
1: 2015 Q1 1 Conventional.Prod 7.31
2: 2015 Q1 1 Unconventional.Prod 10.69
3: 2015 Q1 2 Conventional.Prod 11.78
4: 2015 Q1 2 Unconventional.Prod 15.22
5: 2015 Q1 3 Conventional.Prod 9.44
6: 2015 Q1 3 Unconventional.Prod 15.56
7: 2015 Q1 4 Conventional.Prod 7.34
8: 2015 Q1 4 Unconventional.Prod 7.66
9: 2015 Q1 NA Conventional.Prod 28.72
10: 2015 Q1 NA Unconventional.Prod 30.28
【问题讨论】:
-
我不确定问题是否可以通过使用
aes_group_order来解决,但不确定如何正确实施。
标签: r ggplot2 data.table dplyr