修复R中散点图中的重叠节点和节点标签

时间:2013-10-23 04:07:43

标签: r plot scatter-plot pch

我正在尝试使用散点图在R中绘制一些数据。这是我用于绘图的代码

data <- read.table(filename, header=FALSE);
colnames(data) <- c("xlabel", "ylabel", "xvalue", "yvalue", "class");   
df <- data.frame(data["xlabel"], data["ylabel"],data["xvalue"], data["yvalue"], data["class"]);
with(df, plot(xvalue, yvalue,       
    pch=c(16,17)[class],
    col=c("red", "blue", "green")[class],
    main="Tittle",
))

#label the nodes    
with(df, text(xvalue+300, yvalue, cex=0.5, sprintf("(%s, %s)", xlabel, ylabel)));

然而,当2个节点彼此关闭,甚至更糟糕的重叠时,如here所示,很难区分节点及其标签。所以我的问题是:  1.如何以不同方式设置节点的笔触和填充颜色以区分重叠节点?  2.无论如何都要使节点标签表现得更聪明,例如在重叠的情况下调整它们的位置?也许,有一些库可以提供这个选项吗?

如果您想测试数据,请输入以下数据:

2 6 6990 4721 1 
2 7 6990 4643 2 
1 4 13653 3294 2 
3 7 4070 4643 1 
2 8 6990 6354 1 
3 8 4070 6354 1 
1 2 13653 6990 1 
1 7 13653 4643 2 
3 5 4070 3349 2 
1 8 13653 6354 1 
3 6 4070 4721 1 
2 4 6990 3294 2 
1 5 13653 3349 2 
1 6 13653 4721 1 
3 4 4070 3294 2 
2 5 6990 3349 2 
5 8 3349 6354 1 

谢谢,

1 个答案:

答案 0 :(得分:1)

一个简单的解决方法是在左侧和右侧交替放置标签。我已经按x值然后y值对数据集进行了排序,因此附近的点在数据集中接近。

library(plyr)
df <- arrange(df, xvalue, yvalue)
offset <- rep(c(-300, 300), length.out = nrow(df))

with(df, plot(xvalue, yvalue,       #as before
    pch=c(16,17)[class],
    col=c("red", "blue", "green")[class],
    main="Tittle",
))

with(df, text(xvalue + offset, yvalue, cex=0.5, sprintf("(%s, %s)", xlabel, ylabel)))

如果你使用格子或ggplot(而不是基础图形),那么directlabels包有一个direct.label函数可以自动定位你的标签。

相关问题