【问题标题】:ggplot2: Facetted lineplot with baselineggplot2:带基线的分面线图
【发布时间】:2014-05-02 15:28:56
【问题描述】:

我想创建一个多面线图。在每个子图中,将一个 y 值(y1 或 y2)与基线进行比较。 y 值和基线应以不同的颜色显示,但此配色方案应在每个子图中保持一致。作为一个传说,我只需要 2 个条目:“y 值”和“基线”,因为每个子图的标题都命名了要比较的 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 数据集和重复的基线数据。然后,我在组列方面使用了分面。不幸的是,这导致使用许多不同的颜色和一个巨大的传说。有没有更好的方法来做到这一点?

【问题讨论】:

  • classes 真的是分类的还是数字的,但您只想将“10m”等作为轴标签?
  • 确实是分类的。该示例来自机器学习领域,其中类别代表不同的训练集。

标签: r ggplot2 facet


【解决方案1】:

这是你的想法吗?

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)

【讨论】:

  • 这正是我想要的。我在格式化原始数据方面做得很糟糕,非常感谢您提供优雅的融化解决方案!
【解决方案2】:

您可能正在寻找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 ~.)

导致:

【讨论】:

  • 谢谢,但 eipi10 的解决方案无需手动格式化即可完成工作。
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多