如何将颜色的逻辑'slope > 0'
转换为更复杂的条件?
如果斜率> 0,则为红线。 如果斜率== 0,则为蓝线。 如果斜率<0,则为黑线。
# setup
library(dplyr)
library(ggplot2)
library(lazyeval)
set.seed(205)
dat = data.frame(t=rep(1:2, each=10),
pairs=rep(1:10,2),
value=rnorm(20))
dat$value[dat$pairs==1] <- 1 # forgot to set one pair to slope==0
# function
plotFun <- function(df, groupBy, dv, time) {
ggplot(df %>% group_by_(groupBy) %>%
mutate_(slope = interp(~(dv2[time2==2] - dv2[time2==1])/(2-1),
dv2=as.name(dv),
time2=as.name(time))),
aes_string(time, dv, group = groupBy,
colour = 'slope > 0')) +
scale_colour_manual(values=c("red", "black")) +
geom_point() +
geom_line() +
stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
}
# plot
plotFun(dat, "pairs", "value", "t")
答案 0 :(得分:0)
我不确定为什么要为此制作单独的功能。我会这样做
aggregate(Names ~ Category, data=df, FUN=function(x) length(unique(x)))
Category Names
1 0 2
2 1 1
我已经为斜率添加了一列,根据成对分组的值计算并使用ggplot中的group-method。颜色的条件我在线条的审美。因为if-statements因为原始的图例标题太长了所以我把它关掉了。
希望有所帮助。
答案 1 :(得分:0)
@ lukeA的评论对我有用:
# setup
library(dplyr)
library(ggplot2)
library(lazyeval)
set.seed(205)
dat = data.frame(t=rep(1:2, each=10),
pairs=rep(1:10,2),
value=rnorm(20))
dat$value[dat$pairs==1] <- 1 # forgot to set one pair to slope==0
# function
plotFun <- function(df, groupBy, dv, time) {
ggplot(df %>% group_by_(groupBy) %>%
mutate_(slope = interp(~(dv2[time2==2] - dv2[time2==1])/(2-1),
dv2=as.name(dv),
time2=as.name(time))),
aes_string(time, dv, group = groupBy,
colour = ifelse(slope>0,"blue",
ifelse(slope==0,"black","red"))) +
scale_color_identity() +
geom_point() +
geom_line() +
stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
}
# plot
plotFun(dat, "pairs", "value", "t")