如何在R图中缩放点?

时间:2013-05-04 15:08:22

标签: r plot scale

我有40对鸟,每只雄性和雌性的颜色都得分。颜色分数是分类变量(范围为1到9)。我想绘制男性和女性对颜色组合的频率。我必须创建一个'table',其中包含每个组合的数量(1 / 1,1 / 2,1 / 3,... 9 / 7,9 / 8,9 / 9),然后将其转换为一个名为的向量'Colour_Count'。我想在'plot'中使用'Colour_Count'作为'cex'参数来缩放每种颜色组合的大小。由于从表中读取数据的顺序,这不起作用。如何使用每种颜色组合的频率创建矢量以缩放我的绘图点?

请参阅以下数据和代码:

## Dataset pairs of males and females and their colour classes
Pair_Colours <- structure(list(Male = c(7, 6, 4, 6, 8, 8, 5, 6, 6, 8, 6, 6, 5, 
7, 9, 5, 8, 7, 5, 5, 4, 6, 7, 7, 3, 6, 5, 4, 7, 4, 3, 9, 4, 4, 
4, 4, 9, 6, 6, 6), Female = c(9, 8, 8, 9, 3, 6, 8, 5, 8, 9, 7, 
3, 6, 5, 8, 9, 7, 3, 6, 4, 4, 4, 8, 8, 6, 7, 4, 2, 8, 9, 5, 6, 
8, 8, 4, 4, 5, 9, 7, 8)), .Names = c("Male", "Female"), class = "data.frame", row.names = c(NA, 
40L))

Pair_Colours[] <- as.data.frame(lapply(Pair_Colours, factor, levels=1:9))

## table of pair colour values (colours 1 to 9 - categoricial variable)
table(Pair_Colours$Male, Pair_Colours$Female)

Colour_Count <-  as.vector(table(Pair_Colours$Male, Pair_Colours$Female)) #<- the problem occurs here

## plot results to visisually look for possible assortative mating by colour
op<-par(mfrow=c(1,1), oma=c(2,4,0,0), mar=c(4,5,1,2), pty = "s")
plot(1,1, xlim = c(1, 9), ylim = c(1, 9), type="n", xaxt = "n", yaxt = "n", las=1, bty="n", cex.lab = 1.75, cex.axis = 1.5, main = NULL, xlab = "Male Colour", ylab = "Female Colour", pty = "s")
axis(1, at = seq(1, 9, by = 1), labels = T, cex.lab = 1.5, cex.axis = 1.5, tick = TRUE, tck = -0.015, lwd = 1.25, lwd.ticks = 1.25)
axis(2, at = seq(1, 9, by = 1), labels = T, cex.lab = 1.5, cex.axis = 1.5, tick = TRUE, tck = -0.015, lwd = 1.25, lwd.ticks = 1.25, las =2)
points(Pair_Colours$Male, Pair_Colours$Female, pch = 21, cex = Colour_Count, bg = "darkgray", col = "black", lwd = 1)

1 个答案:

答案 0 :(得分:4)

您可以使用库plyr的函数ddply()汇总数据,然后使用此新数据框来绘制数据。计数位于新数据框的V1列中。

library(plyr)
df<-ddply(Pair_Colours,.(Male,Female),nrow)
df
   Male Female V1
1     3      5  1
2     3      6  1
3     4      2  1
4     4      4  3

points(df$Male, df$Female, pch = 21, cex = df$V1, 
               bg = "darkgray", col = "black", lwd = 1)

UPDATE - 使用聚合

的解决方案

其他可能性是使用函数aggregate()。首先,添加仅包含值1的新列N。然后为每个aggregate()N组合添加Male总和Female值。

Pair_Colours$N<-1
aggregate(N~Male+Female,data=Pair_Colours,FUN=sum)

   Male Female N
1     4      2 1
2     6      3 1
3     7      3 1
4     8      3 1
5     4      4 3

enter image description here