我已经写了一个答案here,并希望改进它。
我想要删除show.legend = FALSE
的图例,但它不适用于color
。 geom_path
的{{1}}元素仍保留在图例(Down
和Up
)中。我做错了吗?
是否有另外一种方法可以手动告诉ggplot
只是为了让我们说出图例的最后两个元素(y2015
,y2016
)?
我的代码和输出:
library(ggplot2)
library(reshape2)
library(dplyr)
ggplot2df <- read.table(text = "question y2015 y2016
q1 90 50
q2 80 60
q3 70 90
q4 90 60
q5 30 20", header = TRUE)
df <- ggplot2df %>%
mutate(direction = ifelse(y2016 - y2015 > 0, "Up", "Down"))%>%
melt(id = c("question", "direction"))
ggplot(df, aes(x=question, y = value, color = variable, group = question )) +
geom_point(size=4) +
geom_path(aes(color = direction), arrow=arrow(), show.legend = FALSE)
答案 0 :(得分:2)
我认为正在发生的事情是因为variable
和direction
都映射到了颜色,所以图例有四种不同的颜色值。删除路径图例只会删除箭头,而仅删除点图例会删除点。但无论哪种方式,所有四种颜色仍然分别显示在图例中,分别为点或箭头,因为底层映射仍然有四个值,无论您是否选择在图例中将这四个值显示为点,箭头或两者。
解决这个问题的一种方法是使用填充美学来表达积分。然后路径图例将只有两个值。要执行此操作,您必须使用带有填充内部的点样式(pch值21 - 25)。您还需要更改颜色美学或填充美学的颜色,以便它们不会相同:
ggplot(df, aes(x=question, y = value, group = question)) +
geom_point(size=4, aes(fill=variable), pch=21, color=NA) +
geom_path(aes(color = direction), arrow=arrow(), show.legend=FALSE) +
scale_fill_manual(values=hcl(c(105,285), 100, 50))
答案 1 :(得分:2)
另一种可能性(但更全面的工作)是手动指定箭头的颜色:
library(ggplot2)
library(tidyr)
library(dplyr)
ggplot2df <- read.table(text = "question y2015 y2016
q1 90 50
q2 80 60
q3 70 90
q4 90 60
q5 30 20", header = TRUE)
ggplot2df %>%
mutate(direction = ifelse(y2016 - y2015 > 0, "Up", "Down")) %>%
gather(variable, value, -question, -direction) -> df
gg <- ggplot(df, aes(x=question, y = value, group = question))
gg <- gg + geom_point(aes(color=variable), size=4)
gg <- gg + geom_path(color=c("red", "red", "green", rep("red", 4), "green", "red", "red"),
arrow=arrow(), show.legend=FALSE)
gg