首页 文章

ggplot2中geom_step中的行边框

提问于
浏览
2

我没有't asked a question using this before so forgive me if I haven'在 ggplot2 中使用 geom_step 来尝试为两个独立的两级因子(编码为单个四级因子)的数据生成步长曲线 . 我'd like the first factor (in the below, A vs B) to be represented by colour and the second factor (in the below, 1 vs 2) to be represented by line fill, i.e filled vs white. Here is an edited mock-up of what I'我在寻找:
enter image description here

是否可以在 ggplot2 中为 geom_step 构造的行添加边框?

如果没有,我可以覆盖第二个具有较小线宽和不同颜色的 geom_step 线到"manually"添加线填充吗?我尝试在 scale_colour_manual 术语中添加另一个不同颜色的geom_step,但这只是重复第一个 geom_step 曲线并返回消息"Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale."

示例代码如下 .

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")

1 回答

  • 1

    这不是一个完整的解决方案:

    通过添加另一个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 with line border

    不幸的是,我不确定如何使传说与此一致 .

    更简单的替代方案是使一些线条更轻 . 您可以定义 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

相关问题