RRR
RRR

Reputation: 11

Plotting dummy variables with ggplot2

I actually need help building on this question: ggplot2 graphic order by grouped variable instead of in alphabetical order. I need to produce a similar graph and I actually have a problem with the black points. I have data where column names are dates and rows are filled with 0 or 1 and I need to plot the point if the value is 1. To reproduce, here is a small sample (in my dataset, there is over 300 columns):

df <- data.frame(id=c(1,2,3),
                 "26April1970"=c(0,0,1),
                 "14August1970"=c(0,1,0))

I need to plot the dates on the x axis, match the id to the canton and show the points where the value is 1. Could anyone help?

Upvotes: 1

Views: 1055

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146020

Try this:

plot_data = df %>% 
  ## put data in long format
  pivot_longer(-id, names_to = "colname") %>%
  ## keep only 1s
  filter(value == 1) %>%
  ## convert dates to Date class
  mutate(date = as.Date(colname, format = "%d%B%Y"))
plot_data
# # A tibble: 2 x 4
#      id colname      value date      
#   <dbl> <chr>        <dbl> <date>    
# 1     2 14August1970     1 1970-08-14
# 2     3 26April1970      1 1970-04-26


## plot
ggplot(plot_data, aes(x = date, y = factor(id))) +
  geom_point()

enter image description here


Using this data:

df <- data.frame(id=c(1,2,3),
                 "26April1970"=c(0,0,1),
                 "14August1970"=c(0,1,0), check.names = FALSE)

Upvotes: 1

Duck
Duck

Reputation: 39613

Maybe you are looking for this:

library(ggplot2)
library(dplyr)
library(tidyr)
#Data
df <- data.frame(id=c(1,2,3),
                 "26April1970"=c(0,0,1),
                 "14August1970"=c(0,1,0))
#Code
df %>% pivot_longer(-id) %>%
  ggplot(aes(x=name,y=factor(value)))+
  geom_point(aes(color=factor(value)))+
  scale_color_manual(values=c('transparent','black'))+
  theme(legend.position = 'none')+xlab('Date')+ylab('value')

Output:

enter image description here

Upvotes: 0

Related Questions