ggplot2绘制了与属于不同组的实线相同颜色的虚线 [英] ggplot2 draw dashed lines of same colour as solid lines belonging to different groups
问题描述
我试图为每组绘制2条不同颜色的实线,但也要在这些线条的周围添加相同颜色的虚线,然后添加一个图例。出于某种原因,我在使用虚线或虚线时遇到问题,看起来我正在虚线上绘制两次。我也没有得到正确的图例,我得到错误为'color'添加另一个比例,它将替换现有的比例
。
I am trying to plot 2 solid lines in 2 different colours for each group, but also add dashed lines of the same colour around those lines, then add a legend. For some reason I am having trouble using "dashed" or "dotted", it seems as I am plotting over the dashed lines twice. I am also not getting the legend right, I get the error Adding another scale for 'colour', which will replace the existing scale
.
你能帮我弄清楚我做错了什么吗?
这里是一个示例数据集和我曾经尝试的:
Can you please help me figure out what I am doing wrong? Here is an example dataset and what I have tried:
x <- c(10, 20, 50, 10, 20, 50)
mean = c(52.4, 98.2, 97.9, 74.1, 98.1, 97.6)
group = c(1, 1, 1, 2,2,2)
upper = c(13.64, 89, 86.4, 13.64, 89, 86.4)
lower = c(95.4, 99.8, 99.7, 95.4, 99.8, 99.7)
data <- data.frame(x=x,y=mean, group, upper, lower)
ggplot(data, aes(x = x, y= mean, group = as.factor(data$group), colour=as.factor(data$group))) + geom_line() + geom_point() + geom_line(data=data,aes(x=x, y=lower, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + geom_line(data=data,aes(x=x, y=upper, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + scale_color_manual(values=c("red", "blue")) + scale_colour_discrete(name="Groups")
我也尝试过使用 geom_ribbon
,同样没有分组部分的运气......
I have also tried with geom_ribbon
, again with no luck for the grouping part…
ggplot(data, aes(x = x, y= mean, group = group)) + geom_line() +
geom_ribbon(aes(ymin = lower, ymax = upper)) +
geom_line(aes(y = mean), colour = "Mean")) +
scale_colour_manual(name = "", values = c("Group1", "Group2"))
推荐答案
要添加虚线,您应该添加2 geom_line()
$ C> AES()。没有必要把 data =
和 groups =
参数放在 ggplot()
调用。 linetype =dotted
应放在 aes()
呼叫之外。对于颜色,您只需要一个 scale_color_manual()
。要从图例中删除虚线图案,您可以使用函数 guides()
和 guide_legend()
来覆盖美学。
To add dotted lines you should add 2 geom_line()
call where you provide y values inside aes()
. There is no need to put data=
and groups=
arguments as they are the same as in ggplot()
call. linetype="dotted"
should be placed outside aes()
call. For the colors you need only one scale_color_manual()
. To remove dotted line pattern from legend you can override aesthetic using functions guides()
and guide_legend()
.
ggplot(data, aes(x = x, y= mean, group = as.factor(data$group),
colour=as.factor(data$group))) +
geom_line() + geom_point() +
geom_line(aes(y=lower),linetype="dotted") +
geom_line(aes(y=upper),linetype="dotted")+
scale_color_manual(name="Groups",values=c("red", "blue"))+
guides(colour = guide_legend(override.aes = list(linetype = 1)))
这篇关于ggplot2绘制了与属于不同组的实线相同颜色的虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!