是否可以根据各个图中的点数成对地对不同的Scatter图进行颜色编码

时间:2015-03-09 16:23:27

标签: r

我有一个结构的数据框(mappedUn):

C1  C2  C3  C4  C5  C6
1   1   1   3   1   1
3   3   3   16  3   3
10  NA  10  NA  6   6
11  NA  11  NA  10  11
NA  NA  NA  NA  11  NA
NA  NA  NA  NA  12  NA

注意:我已经删除了上面示例中的条目以使其适合此处,我也更换了列名以使其更简单

我想知道是否有办法在R中对代码散点图进行着色,我使用双方法绘制不同的散点图,我运行的方法是:

pairs(mappedUn[1:6])

这是我得到的:

enter image description here

请注意,有些图表有两个点,有些有3个等等...有没有办法根据它有多少点为上图中的每个图添加不同的背景颜色, 例如4点 - 红色,3黄色,2绿色等

我的最终目标是在视觉上区分具有大量共同点的情节

1 个答案:

答案 0 :(得分:3)

此处的关键是自定义panel内的参数pairs()。请尝试以下操作,看它是否符合您的要求。

n.notNA <- function(x){
  # define the function that returns the number of non-NA values
  return(length(x) - sum(is.na(x)))
}
myscatterplot <- function(x, y){
  # ll is used for storing the parameters for plotting region
  ll <- par("usr") 
  # bg is used for storing the color (an integer) of the background of current panel, which depends on the number of points. When x and y have different numbers of non-NA values, use the smaller one as the value of bg.
  bg <- min(n.notNA(x), n.notNA(y))
  # plot a rectangle framework whose dimension and background color are given by ll and bg
  rect(ll[1], ll[3], ll[2], ll[4], col = bg)
  # fill the rectangle with points
  points(x, y)
}
# "panel = myscatterplot" means in each panel, the plot is given by "myscatterplot()" using appropriate combination of variables
  pairs(data, panel = myscatterplot)

相关问题:R: How to colorize the diagonal panels in a pairs() plot?