我想创建一个刻面线条图。在每个子图中,将一个y值(y1或y2)与基线进行比较。 y值和基线应该通过不同的颜色可视化,但是这种颜色方案应该在每个子图中保持一致。作为传说,我只需要2个条目:" y-value"和"基线",因为每个子图的标题命名要比较的y值。
然而,我只得到了这个(示例代码):
library(ggplot2)
library(reshape)
df = data.frame(c(10,20,40),c(0.1,0.2,0.3),c(0.1,0.4,0.5),c(0.05,0.1,0.2))
names(df)[1]="classes"
names(df)[2]="y1"
names(df)[3]="y2"
names(df)[4]="baseline"
df$classes <- factor(df$classes,levels=c(10,20,40), labels=c("10m","20m","40m"))
dfMelted <- melt(df)
diagram <- ggplot()
diagram <- diagram + theme_bw(base_size=16)
diagram <- diagram + geom_point(data=dfMelted, size=4, aes(x=factor(classes),y=value, colour=variable, shape=variable))
diagram <- diagram + geom_line(data=dfMelted, aes(x=factor(classes),y=value, group=variable, colour=variable))
diagram <- diagram + facet_wrap(~ variable, ncol=1)
diagram
这就是它到目前为止的样子:
我尝试创建组,每组包含一个y数据集和重复的基线数据。然后,我在group-column方面使用了facetting。不幸的是,这导致使用了许多不同的颜色和巨大的传奇。有没有更好的方法呢?
答案 0 :(得分:4)
这是你的想法吗?
df = data.frame(classes=c(10,20,40), y1=c(0.1,0.2,0.3), y2=c(0.1,0.4,0.5),
baseline=c(0.05,0.1,0.2))
df$classes <- factor(df$classes, levels=c(10,20,40),
labels=c("10m","20m","40m"))
# Two melts to create a grouping variable for baseline vs. new value (y1 or y2)
# and another grouping variable for faceting on y1/y2
dfm=melt(df, id.var=c(1,4))
names(dfm)[3] = "y_value"
dfm=melt(dfm, id.var=c(1,3))
ggplot(dfm, aes(x=classes, y=value, group=variable, colour=variable)) +
geom_point() + geom_line() +
theme_bw(base_size=16) +
facet_grid(. ~ y_value)
答案 1 :(得分:1)
您可能正在寻找scale_colour_manual
功能:
ggplot() +
geom_point(data=dfMelted, size=4, aes(x=factor(classes),y=value, colour=variable, shape=variable)) +
geom_line(data=dfMelted, aes(x=factor(classes),y=value, group=variable, colour=variable)) +
scale_colour_manual(values = c("y1" = "red","baseline" = "blue","y2" = "green")) +
theme_bw(base_size=16) +
facet_grid(variable ~.)
导致: