Home > Back-end >  Transform from base R plot to ggplot
Transform from base R plot to ggplot

Time:05-08

I have a based R plot which I have been trying to transform to a ggplot but have no clue how to do it.

I am not sure how to do this as normally for ggplot we create a data frame and insert data we want to plot in the columns. In the plot below, yaxis and points are different data.

## load data
dogs <- read.table("http://www.stat.columbia.edu/~gelman/arm/examples/dogs/dogs.dat", skip = 2)

## some basic transformations & naming
dogsWide <- as.matrix(dogs[,2:ncol(dogs)])
dogsWide <- ifelse(dogsWide=="S",1,0)
dogsWide <- cbind(dogs[,1], dogsWide)
colnames(dogsWide) <- c("dog",paste0("t",0:24))

## order dogs by last shock
o <- order(apply(dogsWide[,2:ncol(dogsWide)], 1, function(x) max(which(x==1))))

## color shocks
colors <- adjustcolor(c("lightblue", "coral2"), alpha.f=.75)


plot(x = 0:26, y = rep(31,27), col = "white", ylim = c(0,31),
     ylab = "dog", xlab = "trial nr",
     main = "learning trajectory for each dog")
for(j in 1:nrow(dogsWide)){
  points(1:25,rep(j,25), pch = 20, cex = 2,
       col = colors[dogsWide[o[j],2:ncol(dogsWide)] 1])
}

This returns a plot as below. enter image description here

CodePudding user response:

library(tidyverse)

dogs <- read.table("http://www.stat.columbia.edu/~gelman/arm/examples/dogs/dogs.dat", skip = 2)

dogsLong <- dogs %>% 
  rename(dog = V1) %>%
  pivot_longer(-dog, names_to = 'trial', values_to = 'shock') %>% 
  mutate(
    trial = parse_number(trial),
    shock = shock == 'S'
  ) %>% 
  group_by(dog) %>% 
  mutate(last_shock = max(which(shock))) %>% 
  ungroup() %>% 
  mutate(dog = as.numeric(fct_reorder(factor(dog), last_shock)))

ggplot(dogsLong, aes(trial, dog, color = shock))  
  geom_point(size = 4, alpha = 0.75)  
  scale_color_manual(
    name = NULL, 
    values = c("lightblue", "coral2"),
    labels = c('no shock', 'shock')
  )  
  coord_equal()  
  theme_classic()  
  labs(
    x = 'trial nr',
    title = 'learning trajectory for each dog'
  )

enter image description here

  • Related