无论我尝试了什么,我似乎都无法切换剧情中两个图例元素的位置。
我需要先出现Chats started
,然后再出现Chats completed
。
以下是数据框:
grouped <- structure(list(date = c("2018-07-16", "2018-07-17", "2018-07-18",
"2018-07-19", "2018-07-20", "2018-07-21", "2018-07-22", "2018-07-23",
"2018-07-24", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-28",
"2018-07-29", "2018-07-30", "2018-07-31"), homepage_opens = c(5L,
0L, 0L, 3L, 1L, 2L, 0L, 1L, 0L, 2L, 5L, 0L, 0L, 0L, 0L, 0L),
sitewide_opens = c(39L, 34L, 19L, 62L, 46L, 44L, 16L, 51L,
25L, 66L, 75L, 0L, 0L, 0L, 0L, 0L), chats_started = c(10L,
16L, 9L, 8L, 13L, 13L, 5L, 13L, 4L, 8L, 11L, 0L, 0L, 0L,
0L, 0L), chats_completed = c(7L, 13L, 8L, 4L, 5L, 9L, 6L,
13L, 2L, 7L, 5L, 0L, 0L, 0L, 0L, 0L)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -16L))
这是情节代码:
library(ggplot2)
ggplot(grouped) +
geom_col(aes(x = date, y = chats_started, fill = "Chats started"),
colour = "black",
alpha = 0.5) +
geom_col(aes(x = date, y = chats_completed, fill = "Chats completed"),
colour = "black",
alpha = 0.5) +
geom_text(aes(x = date, y = chats_started, label = chats_started),
colour = "black",
hjust = -0.15,
vjust = -1.5,
size = 3) +
geom_text(aes(x = date, y = chats_completed, label = chats_completed),
hjust = -0.15,
vjust = -1.5,
size = 3,
colour = "black") +
labs(title = paste0("Chat Analysis\n(started vs. completed)"),
x = "Date",
y = "Count") +
theme(legend.position = "top",
legend.title = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
axis.text = element_text(colour = "black")) +
scale_fill_manual(values = c("Chats completed" = "lightgreen", "Chats started" = "sandybrown"),
labels = c("Chats completed", "Chats started"))
这就是我最终得到的结果:
答案 0 :(得分:1)
您只需要guide = guide_legend(reverse=TRUE)
,如Cookbook for R所示:
ggplot(grouped) +
geom_col(aes(x = date, y = chats_started, fill = "Chats started"),
colour = "black",
alpha = 0.5) +
geom_col(aes(x = date, y = chats_completed, fill = "Chats completed"),
colour = "black",
alpha = 0.5) +
geom_text(aes(x = date, y = chats_started, label = chats_started),
colour = "black",
hjust = -0.15,
vjust = -1.5,
size = 3) +
geom_text(aes(x = date, y = chats_completed, label = chats_completed),
hjust = -0.15,
vjust = -1.5,
size = 3,
colour = "black") +
labs(title = paste0("Chat Analysis\n(started vs. completed)"),
x = "Date",
y = "Count") +
theme(legend.position = "top",
legend.title = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
axis.text = element_text(colour = "black")) +
scale_fill_manual(values = c("Chats completed" = "lightgreen", "Chats started" = "sandybrown"),
labels = c("Chats completed", "Chats started"),
guide = guide_legend(reverse=TRUE))
对于它的价值,搜索显示与图例排序有关的几个不同问题以及对类似问题的各种解决方案:
但是,这些问题的答案中没有一个显示出针对颠倒图例顺序这一特定问题的简单解决方案,因此,我提供此答案,而不是试图判断是否有很多问题之一实际上足够接近以标记为重复。