marvinjonathcn
marvinjonathcn

Reputation: 67

Create a graph from a binary column in a dataframe - R

I need to create a point graph using the "ggplot" library based on a binary column of a dataframe.

df <- c(1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1)

I need a point to be created every time the value "1" appears in the column, and all points are on the same graph. Thanks.

Upvotes: 1

Views: 1154

Answers (3)

kmacierzanka
kmacierzanka

Reputation: 825

If the binary column you talk about is associated to some other variables, then I think this might work:

(I've just created some random x and y which are the same length as the binary 0, 1s you provided)

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()

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76565

Something like this?

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

It only plots points where df == 1, not the zeros. If you also want those, don't run the code line starting is.na(y).

Upvotes: 1

mysteRious
mysteRious

Reputation: 4304

Not sure exactly what you are asking, but here are a few options. Since your data structure is not a data frame, I've renamed it test. First, dotplot with ggplot:

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

enter image description here

Or you could do the same thing as a bar:

qplot(test, geom="bar")

enter image description here

Or, a primitive base R quick look:

plot(test, pch=16, cex=3)

enter image description here

Upvotes: -1

Related Questions