【问题标题】:Border for line in geom_step in ggplot2ggplot2中geom_step中线条的边框
【发布时间】:2014-05-01 11:30:54
【问题描述】:

我之前没有使用过这个问题,所以如果我没有提供足够详细的需求/解释,请原谅我。我在ggplot2 中使用geom_step 尝试为具有两个单独的两级因子(编码为单个四级因子)的数据生成阶梯曲线。我希望第一个因素(在下面,A vs B)用颜色表示,第二个因素(在下面,1 vs 2)用线条填充表示,即填充与白色。这是我正在寻找的经过编辑的模型:

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

如果没有,我可以用更小的线宽和不同的颜色覆盖第二条geom_step 线以“手动”添加线填充吗?我尝试在 scale_colour_manual 术语中添加另一个具有不同颜色的 geom_step,但这只是复制了第一个 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)
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=]。但这不会影响传说

标签: r ggplot2


【解决方案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")

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

一个更简单的选择是使一些线条更轻。你可以定义一个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")

【讨论】:

    猜你喜欢
    • 2019-09-21
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多