【问题标题】:Creating a facet_wrap plot with ggplot2 with different annotations in each plot使用 ggplot2 创建一个 facet_wrap 图,每个图中都有不同的注释
【发布时间】:2010-01-12 16:46:36
【问题描述】:

我正在使用 ggplot2 来探索在基于代理的模型上进行的一些测试的结果。该模型可以在每个实现的三个回合之一结束,因此我感兴趣的是玩家效用在游戏结束的回合及其在 2D 空间中的相对位置方面有何不同。

所有这一切都是说我已经生成了一个 facet_wrap 图来显示每一轮,但我还想用 cor(x,y) 注释每个图,用于每个方面表示的数据子集。有没有办法告诉 ggplot2 我希望注释使用由 facet_wrap 生成的数据子集?这是我到目前为止的代码,以及它正在生成的代码

library(ggplot2)

# Load data
abm.data<-read.csv("ABM_results.csv")

# Create new colun for area of Pareto set
attach(abm.data)
area<-abs(((x3*(y2-y1))+(x2*(y1-y3))+(x1*(y3-y2)))/2)
abm.data<-transform(abm.data,area=area)
detach(abm.data)

# Compare area of Pareto set with player utility
png("area_p1.png",res=100,pointsize=20,height=500,width=1600)
area.p1<-ggplot(abm.data,aes(x=area))+geom_point(aes(y=U1_2,colour="Player 1",alpha=0.4))+facet_wrap(~round,ncol=3)+
    annotate("text",0.375,-1.25,label=paste("rho=",round(cor(abm.data$area,abm.data$U1_2),2)), parse=TRUE)+
    scale_colour_manual(values=c("Player 1"="red"))
area.p1+xlab("Area of Pareto Set")+ylab("Player Utility at Game End")+
    opts(title="Final Player 1 Utility by Pareto Set Size and Round Game Ends",legend.position="none")
dev.off()


(来源:drewconway.com

如你所见,有两个问题:

  1. \rho 值是完整数据集,而不是“round”的子集。有没有办法仅根据每个图中显示的数据来打印 cor(x,y)?
  2. 注释应该是“\rho=some_value”,但我得到的是“=(\rho,value);”有没有办法解决这个问题?

【问题讨论】:

    标签: r graph ggplot2


    【解决方案1】:

    要解决第二个问题,请使用

    annotate("text", 0.375, -1.25,
             label=paste("rho==", round(cor(abm.data$area, abm.data$U1_2), 2)),
             parse=TRUE)
    

    "rho==".

    编辑:这是解决第一个问题的解决方案

    library("plyr")
    library("ggplot2")
    
    set.seed(1)
    df <- data.frame(x=rnorm(300), y=rnorm(300), cl=gl(3,100))   # create test data
    df.cor <- ddply(df, .(cl), function(val) sprintf("rho==%.2f", cor(val$x, val$y)))
    
    p1 <- ggplot(data=df, aes(x=x)) +
                 geom_point(aes(y=y, colour="col1", alpha=0.4)) +
                 facet_wrap(~ cl, ncol=3) +
                 geom_text(data=df.cor, aes(x=0, y=3, label=V1), parse=TRUE) +
                 scale_colour_manual(values=c("col1"="red")) +
                 opts(legend.position="none")
    print(p1)
    

    【讨论】:

    • 我推荐 geom_text(aes(x = 0, y = 3, label = V1), ...),而不是 cbinding x 和 y 到 df.cor,我推荐 geom_text(aes(x = 0, y = 3, label = V1), ...)
    • 太棒了,太完美了!我正要恢复通过 Inkscape 手动添加值...
    • 在跨面书写时,有什么方法可以使用 substitute 等数学符号?
    【解决方案2】:

    对于为每个方面添加细分,可能会提出相同的问题。我们可以通过geom_segment而不是annotate("segment",...)来解决这些一般问题,对于geom_foo,我们可以定义一个data.frame来存储geom_foo的数据。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多