Question

I'm trying to plot some data in R using scatter plot. Here's the code I had for plotting

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

However, when 2 nodes are closed to each other, or even worse overlapping, as seen in here, it's very hard to distinguish the nodes and their labels. So my questions are: 1. How can I set the stroke and fill color of nodes differently to distinguish the overlapping nodes? 2. Is there anyway to make the node labels behave smarter, such as adjusting their locations in case of overlapping? Maybe, there is some library available that allows that option?

Here's the data if you want to test it:

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 

Thanks,

Was it helpful?

Solution

A simple fix is to alternate placing labels on the left and right. I've ordered the dataset by x-value then y-value, so nearby points are near in the dataset.

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

If you use lattice or ggplot (rather than base graphics) instead then the directlabels package has a direct.label function that automatically positions your labels.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top