从数据框中的二进制列创建图形-R

时间:2020-06-17 10:40:57

标签: r

我需要使用“ 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”时,都需要创建一个点,并且所有点都在同一图形上。谢谢。

3 个答案:

答案 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)

不确定您要问的是什么,但是这里有一些选择。由于您的数据结构不是数据框架,因此我将其重命名为test。首先,用ggplot绘制dotplot:

library(ggplot2)
ggplot(as.data.frame(test), aes(x=test)) + geom_dotplot()

enter image description here

或者您可以做与酒吧相同的事情:

qplot(test, geom="bar")

enter image description here

或者,一个基本的R快速浏览:

图(测试,pch = 16,cex = 3)

enter image description here