Using Geom_Segment in R

3.8k Views Asked by At

I am trying to create a plot in R using Geom_Segment. I am stuck with an error that says I need to input yend but I am inputting it already... this is my code:

library(ggplot2) 
library(data.table)
library(magrittr)


dataset$From<-Sys.Date()
format(dataset$From, format="%Y-%m-%dT%H:%M:%OS")
dataset$To<-Sys.Date()
format(dataset$To, format="%Y-%m-%dT%H:%M:%OS")



ggplot(dataset, aes(x=datetime_start, y=dataset$Audit_Title, 
color=dataset$Employee_Name)) +
  geom_segment(aes(x=dataset$From,xend=dataset$To,y=dataset$Audit_Title,yend=dataset$Audit_Title),size=20)+
  scale_colour_discrete(guide=guide_legend(override.aes=list(size=15))) +
ggtitle("Audit by Employee Timeline") + xlab("") + ylab("") + theme_bw()

SAMPLE DATA: Here is the sample data

This is how I changed the code below to take in the data from Excel I inputted into Power BI:

library(ggplot2)
library(dplyr)

# transform into date
dataset <- dataset %>% 
  mutate_at(vars(dataset$From, dataset$To),
            .funs = function(tt) readr::parse_date(as.character(tt),
                             format = "%m/%d/%Y"))

ggplot(dataset)+
  geom_segment(aes(x=dataset$From, xend=dataset$To,
                   y=dataset$Employee_Name, yend=dataset$Employee_Name))
1

There are 1 best solutions below

3
On

First of all, ideally you would share your data as a dput(dataset). If you can't share real data, you should make a minimal reproducible example and share that. See here

Here's your data

library(ggplot2)
library(dplyr)
df <- 
read.table(
text =  
"01/03/2020 03/16/2020 Supply_Chain John_Smith 
05/08/2020 08/20/2020 Business_Unit Karen_Scott")

names(df) <- c("From", "To", "Audit_Title", "Employee_Name")
# transform into date
df <- df %>% 
  mutate_at(vars(From, To),
            .funs = function(tt) readr::parse_date(as.character(tt),
                             format = "%m/%d/%Y"))

Now do the actual plot by selecting the proper x xend and having y be the employee (y=yend).

ggplot(df)+
  geom_segment(aes(x=From, xend=To,
                   y=Employee_Name, yend=Employee_Name))

Which produces

enter image description here

If you want fancy colors, labels and stuff go ahead and check the proper documentation for ggplot. See here