R中的问题排序和绘图

时间:2014-11-19 01:37:03

标签: r

我需要解决一个问题:使用R包中的ChickWeight数据,计算每只Chick的平均重量。然后根据每种饮食的重量订购鸡肉。然后绘制这些有序重量,每种饮食的颜色不同,这样每只饮食的雏鸡顺序从最低到最高。对于数据符号,请使用Chick标识。 enter image description here

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

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。我真的需要帮助!!非常感谢你!!

2 个答案:

答案 0 :(得分:3)

插图:

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")

enter image description here

答案 1 :(得分:0)

使用基本图形很容易实现:

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
)

enter image description here