Lucas
Lucas

Reputation: 1177

R. How to avoid lines connecting dots in dotplot

I made a plot using plot() using RStudio. enter image description here

x = X$pos
y = X$anc
z = data.frame(x,y)

#cut in segments
my_segments = c(52660, 106784, 151429, 192098, 233666, 
                273857, 307933, 343048, 373099, 408960, 
                441545, 472813, 497822, 518561, 537471, 
                556747, 571683, 591232, 599519, 616567, 
                625727, 633744)
my_cuts = cut(x,my_segments, labels = FALSE)
my_cuts[is.na(my_cuts)] = 0

This is the code:

#create subset of segments
z_alt = z
z_alt[my_cuts %% 2 == 0,] = NA

#plot green, then alternating segments in blue
plot(z, type="p", cex = 0.3,pch = 16,
     col="black", 
     lwd=0.2,
     frame.plot = F,
     xaxt = 'n', # removes x labels,
     ylim = c(0.3, 0.7),
     las = 2,
     xlim = c(0, 633744),
     cex.lab=1.5, # size of axis labels
     ann = FALSE, # remove axis titles
     mgp = c(3, 0.7, 0)) 

lines(z_alt,col="red", lwd=0.2)

# adjust y axis label size
par(cex.axis= 1.2, tck=-0.03)

If you see, some black dots are separated, but other black dots have red connecting lines. Does anyone know how to remove these annoying lines?. I just want black and red dots. Many thanks

Upvotes: 0

Views: 533

Answers (2)

AshOfFire
AshOfFire

Reputation: 676

The problem here is that you are using lines to add your z_alt. As the name of the function suggests, you will be adding lines. Use points instead.

z <- runif(20,0,1)
z_alt <- runif(20,0.8,1.2)
plot(z, type="p", col="black", pch = 16, lwd=0.2, ylim = c(0,1.4)) 
points(z_alt, col = "red", pch = 16, lwd = 0.2)

Upvotes: 1

Roman
Roman

Reputation: 17648

there is no need to call the points in a second function. you can try to directly set the color in the plot function using a color vector.

#  create some data as you have not provided some
set.seed(123)
df <- data.frame(x=1:100,y=runif(100))

# some sgment breaks
my_segments <- c(0,10,20,50,60)
gr <- cut(df$x, my_segments,labels = FALSE, right = T)
gr[is.na(gr)] <- 0

# create color vector with 1 == black, and 2 == red
df$color <- ifelse(gr %% 2 == 0, 1, 2)

# and the plot
plot(df$x, df$y, col = df$color, pch = 16)

enter image description here

Upvotes: 1

Related Questions