Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

plot - R—Plotting the number of points that overlap rather than a symbol

I am doing a plot where there are overlapping values because both x and y are discrete. I have searched and found examples where they make the area of the dot proportional to the number of data points that overlap at a single x-y point, but what I'd like to be able to do is to plot the number of points that overlap. So, for example, if the point (5, 7) were repeated 7 times, I'd like it to plot the number "7" at that point rather than a symbol. I feel like this should be possible but can't figure out how to do it.

Here is some code that generates the plot I am hoping to do this for:

worker <- 1:10

defects <- t(matrix(rbinom(200, 100, 0.1), ncol=10))

matplot(worker, defects)

Thanks in advance for any help you can provide!

question from:https://stackoverflow.com/questions/65829427/r-plotting-the-number-of-points-that-overlap-rather-than-a-symbol

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to SO!

You need to get the "count" of observations for each x,y pair and then you can use annotation to get your plot. Here's an example using data.table and ggplot2:

library(data.table)
library(ggplot2)

# using a sample dataset 
dat <- as.data.table(mtcars)

# creating a variable called "count" for no. of overlaps for a given (gear,carb) pair 
ggplot(dat[, .(count = .N), by = .(gear, carb)]) + 
  geom_text(aes(x = gear, y= carb, label = count) )

enter image description here

You can format the text any way you want (font, size etc.) or combined with other items e.g. add geom_point so you see a point along with the text - you can set the transparency or size based on the number of overlapping points (count in this example).

# Using nudge_x, nudge_y to avoid marker and text overlap
ggplot(dat[, .(count = .N), by = .(gear, carb)]) + 
  geom_text(aes(x = gear, y= carb, label = count), nudge_x = 0.05, nudge_y = 0.05) + 
  geom_point(aes(x = gear, y = carb), color = 'dark red')

enter image description here

Hope this is helpful!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...