R - 绘制重叠的点数而不是符号
R—Plotting the number of points that overlap rather than a symbol
我正在绘制一个有重叠值的图,因为 x 和 y 都是离散的。我已经搜索并找到了示例,其中它们使点的面积与在单个 x-y 点重叠的数据点的数量成正比,但我想要做的是绘制 number 个重叠点。因此,例如,如果点 (5, 7) 重复 7 次,我希望它在该点绘制数字“7”而不是符号。我觉得这应该是可能的,但不知道该怎么做。
这里有一些代码可以生成我希望这样做的情节:
worker <- 1:10
defects <- t(matrix(rbinom(200, 100, 0.1), ncol=10))
matplot(worker, defects)
在此先感谢您提供的任何帮助!
欢迎来到 SO!
您需要获取每个 x,y 对的观察“计数”,然后您可以使用注释来获取您的绘图。这是一个使用 data.table
和 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) )
您可以任意设置文本格式(字体、大小等)或与其他项目结合使用,例如添加 geom_point
这样您就可以在文本旁边看到一个点 - 您可以根据重叠点的数量设置透明度或大小(本例中为 count
)。
# 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')
希望对您有所帮助!
我正在绘制一个有重叠值的图,因为 x 和 y 都是离散的。我已经搜索并找到了示例,其中它们使点的面积与在单个 x-y 点重叠的数据点的数量成正比,但我想要做的是绘制 number 个重叠点。因此,例如,如果点 (5, 7) 重复 7 次,我希望它在该点绘制数字“7”而不是符号。我觉得这应该是可能的,但不知道该怎么做。
这里有一些代码可以生成我希望这样做的情节:
worker <- 1:10
defects <- t(matrix(rbinom(200, 100, 0.1), ncol=10))
matplot(worker, defects)
在此先感谢您提供的任何帮助!
欢迎来到 SO!
您需要获取每个 x,y 对的观察“计数”,然后您可以使用注释来获取您的绘图。这是一个使用 data.table
和 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) )
您可以任意设置文本格式(字体、大小等)或与其他项目结合使用,例如添加 geom_point
这样您就可以在文本旁边看到一个点 - 您可以根据重叠点的数量设置透明度或大小(本例中为 count
)。
# 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')
希望对您有所帮助!