在ggplot2中的geom_step中如何为线条添加边框

4
我以前没有用过这种方式提问,如果我没有提供所需内容或没有足够详细的解释,请原谅。我正在使用ggplot2中的geom_step尝试为具有两个单独的二级因子(编码为单个四级因子)的数据生成阶梯曲线。我希望以下第一个因子(在下面是A vs B)由颜色表示,第二个因子(在下面是1 vs 2)由线条填充表示,即填充与白色。这是我正在寻找的东西的修改后仿制品: enter image description hereggplot2中的geom_step构建的线条上添加边框是否可能?
如果不行,我能否重叠一个带有较小线宽和不同颜色的第二个geom_step线,以“手动”添加线条填充?我已经尝试在scale_colour_manual项中添加具有不同颜色的另一个geom_step,但这只是复制了第一个geom_step曲线并返回消息“ 'colour'的比例已经存在。添加另一个比例尺'colour',将替换现有比例尺。”
以下是示例代码。
events <- rep(c(0,1,2,3,4),4)
individual <- (as.factor(rep(c("A1","A2","B1","B2"),each=5)))
step <- c(1,2,3,4,5,3,4,5,6,7,5,6,7,8,9,7,8,9,10,11)
df <- data.frame(events,individual,step)

ggplot(df, aes(x=events, group=individual, colour=individual, y=step)) + 
  geom_step(size=1.8) +
  scale_colour_manual(values=c("green2","green2", "orange", "orange"), name="Individual")

如果你的图表是 g,那么使用 g + geom_step(data=df[grepl("2",individual),] , col="white", size=1) 来添加一个白色条纹。[请注意在 geom_step 中需要再添加一个 data= 参数]. 但这不会影响图例。 - user20650
1个回答

2

这并不是完整的解决方案:

通过添加另一个geom_step命令,可以很容易地添加一个白色条纹:

events<-rep(c(0,1,2,3,4),4)
individual<-(as.factor(rep(c("A1","A2","B1","B2"),each=5)))
step<-c(1,2,3,4,5,3,4,5,6,7,5,6,7,8,9,7,8,9,10,11)
filled <- rep(c(FALSE,TRUE),each=5)

data_frame<-data.frame(events,individual,step,filled)
ggplot(data_frame, aes(x=events, group=individual, colour=individual, y=step)) + 
geom_step(size=1.8) +
scale_colour_manual(values=c("green2","green2", "orange", "orange"), name="Individual") +
geom_step(data=df[df$filled,], size=1.1, colour="white")

带有线边框的ggplot

很遗憾,我不确定如何使图例与此一致。

一个更简单的替代方案是使一些线条变浅。您可以定义一个lighten_colour函数:

lighten_colour <- function(colour, lightness=0.5) {
    # lightness should be between 0 and 1
    white <- col2rgb("white") / 255
    colour <- col2rgb(colour) / 255
    rgb(t(white*lightness + colour*(1-lightness)))
}

使用这个来设置绘图颜色。

ggplot(data_frame, aes(x=events, group=individual, colour=individual, y=step)) + 
geom_step(size=1.8) +
scale_colour_manual(values=c(lighten_colour("green2"),
                             "green2",
                             lighten_colour("orange"),
                             "orange"),
                    name="Individual")

ggplot with lighter colours


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接