在 ggplot R 中按销售额设置堆积面积图的顺序
Set order of stacked area graphs by sales in ggplot R
你能告诉我2013年如何根据销售额从上到下排序堆叠图吗?例如,2013 年销售额在 D 组中最高,所以我希望在该类别中始终处于顶部等等。
df <- data.frame (Year = c("2010", "2010", "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
Sale = c(100,200,50,500,400,200,400,145,100,456,345,321,100,200,250,400),
Group = c("A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D"))
df$Year <- as.integer(df$Year)
ggplot(df, aes(x = Year, y = Sale, fill = Group)) +
geom_area()
您需要使用 forcats
中的 fct_reorder()
通过 Sale
对因子 Group
重新排序:
df %>%
mutate(Group = fct_reorder(Group, desc(Sale))) %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
要在特定年份完成,我执行了以下操作。
ls <- df %>% filter(Year == 2013) %>% arrange(desc(Sale)) %>% select(Group)
df$Group <- factor(df$Group, levels = ls$Group)
df %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
这是手动重新排序。
你能告诉我2013年如何根据销售额从上到下排序堆叠图吗?例如,2013 年销售额在 D 组中最高,所以我希望在该类别中始终处于顶部等等。
df <- data.frame (Year = c("2010", "2010", "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
Sale = c(100,200,50,500,400,200,400,145,100,456,345,321,100,200,250,400),
Group = c("A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D","A", "B", "C", "D"))
df$Year <- as.integer(df$Year)
ggplot(df, aes(x = Year, y = Sale, fill = Group)) +
geom_area()
您需要使用 forcats
中的 fct_reorder()
通过 Sale
对因子 Group
重新排序:
df %>%
mutate(Group = fct_reorder(Group, desc(Sale))) %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
要在特定年份完成,我执行了以下操作。
ls <- df %>% filter(Year == 2013) %>% arrange(desc(Sale)) %>% select(Group)
df$Group <- factor(df$Group, levels = ls$Group)
df %>%
ggplot(aes(x = Year, y = Sale, fill = Group)) +
geom_area()
这是手动重新排序。