1

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.

1
  • 2
    By "point graph" do you mean scatter plot? If so, you need to provide another variable to define the second dimension. If not, what is your expected output? What have you tried so far? Commented Jun 17, 2020 at 10:47

3 Answers 3

2

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This was what I needed. Thanks.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.