【问题标题】:Sorting and ploting problems in RR中的排序和绘图问题
【发布时间】:2014-11-19 01:37:03
【问题描述】:

我需要解决一个问题:使用 R 包中的 ChickWeight 数据,计算每个 Chick 的平均重量。然后根据每种饮食的重量订购鸡肉。然后绘制这些有序的重量,为每个饮食使用不同的颜色,以便对于每个饮食,小鸡的顺序从最低重量到最高重量进行。对于数据符号,使用小鸡身份。

我已经尝试了一段时间,但仍然找不到答案。我试图创建一个新的数据框,但我无法让它工作:

WeightMean = with(ChickWeight, tapply(weight, list(Chick), mean))
a = as.data.frame(WeightMean) 
a$Diet = c(rep(1, 20), rep(2, 10), rep(3, 10), rep(4, 10))
a$Diet = ifelse(a$Diet == 1, "Diet1", ifelse(a$Diet == 2, "Diet2", ifelse(a$Diet == 3, "Diet3", "Diet4")))

a_diet1 = a[1:20,]
a_diet2 = a[21:30,]
a_diet3 = a[31:40,]
a_diet4 = a[41:50,]

sort(a_diet1)
sort(a_diet2)
sort(a_diet3)
sort(a_diet4)

a$WeightMean = c(a_diet1, a_diet2, a_diet3, a_diet4)
ChickWeight.a_diets = a_diets

plot(a, col=factor(a$Diet))

我认为解决这个问题的最好方法是使用 ggplot。我真的需要帮助!!非常感谢!!

【问题讨论】:

    标签: r


    【解决方案1】:

    插图:

    library(data.table); library(ggplot2)
    # to convert ChickWeight to data table
    df = as.data.table(as.data.frame(ChickWeight)) 
    # to get the average weight based on Diet, Chick grouping
    df2 = df[, list(weight_ave = mean(weight)), by=list(Diet, Chick)]
    # to sort and add indices to column "idx" for easier plotting
    df2 = df2[order(Diet, weight_ave)][, idx := 1:nrow(df2)]
    # code to plot in ggplot2
    ggplot(data=df2, aes(x=idx, y=weight_ave)) +  
      theme_bw() +
      geom_point(aes(colour=Diet)) +
      geom_text(aes(label=Chick), size=4, vjust=-0.5) +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank()) +
      xlab("Chick")
    

    【讨论】:

      【解决方案2】:

      使用基本图形很容易完成:

      out <- aggregate(weight ~ Chick + Diet,data=ChickWeight, FUN=mean)
      out <- out[order(out$Diet,out$weight),]
      
      plot(out$weight,type="n")
      grid()
      text(
           out$weight,
           labels=as.character(out$Chick),
           col=as.numeric(out$Diet),
           cex=0.7
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        • 2023-03-25
        • 2012-03-28
        • 2021-04-02
        • 2021-11-29
        • 2019-05-23
        • 1970-01-01
        相关资源
        最近更新 更多