我需要使用“ ggplot”库基于数据帧的二进制列创建点图。
df <- c(1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1)
每当列中出现值“ 1”时,都需要创建一个点,并且所有点都在同一图形上。谢谢。
答案 0 :(得分:2)
如果您所讨论的二进制列与其他一些变量相关联,那么我认为这可能有效:
(我刚刚创建了一些随机的x和y,它们的长度与您提供的二进制0、1相同)
x <- rnorm(22)
y <- x^2 + rnorm(22, sd = 0.3)
df <- data.frame("x" = x, "y" = y,
"binary" = c(1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1))
library(ggplot2)
# this is the plot with all the points
ggplot(data = df, mapping = aes(x = x, y = y)) + geom_point()
# this is the plot with only the points for which the "binary" variable is 1
ggplot(data = subset(df, binary == 1), mapping = aes(x = x, y = y)) + geom_point()
# this is the plot with all points where they are coloured by whether "binary" is 0 or 1
ggplot(data = df, mapping = aes(x = x, y = y, colour = as.factor(binary))) + geom_point()
答案 1 :(得分:1)
像这样吗?
library(ggplot2)
y <- df
is.na(y) <- y == 0
ggplot(data = data.frame(x = seq_along(y), y), mapping = aes(x, y)) +
geom_point() +
scale_y_continuous(breaks = c(0, 1),
labels = c("0" = "0", "1" = "1"),
limits = c(0, 1))
它仅绘制df == 1
处的点,而不绘制零点。如果还需要这些代码,请不要运行以is.na(y)
开头的代码行。
答案 2 :(得分:-1)