R.如何避免在dotplot中连接点的线条

时间:2018-04-26 14:14:14

标签: r plot

我使用RStudio使用plot()制作了一个情节。 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)

如果你看到,一些黑点被分开,但其他黑点有红色连线。有谁知道如何删除这些烦人的线?我只想要黑色和红色的圆点。非常感谢

2 个答案:

答案 0 :(得分:1)

此处的问题是您使用lines添加z_alt。正如函数的名称所示,您将添加行。请改用points

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)

答案 1 :(得分:1)

无需在第二个函数中调用点。您可以尝试使用颜色矢量直接设置绘图功能中的颜色。

#  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