Home > Software design >  How to remove extra lines in ggplot2
How to remove extra lines in ggplot2

Time:06-13

I'm trying to create a graph of survival over time at a number of different sites.

I have a fairly simple dataframe as below

enter image description here

I have used the following code to make the plot:

my_df <- data.frame(x = Survival$time, y = Survival$`% survival`, group = Survival$Site)

ggplot(my_df, aes(x = Survival$time, y = Survival$`% survival`,colour=as.factor("Site")))  
  geom_point(aes(colour = group, group=1))  # Points and color by group
  geom_path(aes(colour=group, group=1), na.value="blank") 
  scale_color_discrete("Site", na.value=NA)  # Change legend title
  xlab("Time in Months")                # X-axis label
  ylab("Percent Survival")                # Y-axis label
  theme(axis.line = element_line(colour = "black", # Changes the default theme
                                 size = 0.24))

However for some reason there seems to be an extra green line and an extra grey line

enter image description here

Just wondering why this may be and what would be the best way to fix this issue

CodePudding user response:

Here a situation where all of the suggestions of @Rui Barradas in the comments are implemented and some other tweaks:

library(tidyverse)
my_df %>% 
  transmute(time = parse_number(X),
            survival = y, group = group) %>% 
  ggplot(aes(x = time, y = survival, colour=factor(group), group=group))  
  geom_point()  
  geom_path(size = 1)  
  scale_color_discrete("group", na.value=NA)  # Change legend title
  labs(title = "Survival", x = "Time in Months", y = "Percent Survival")   
  scale_fill_brewer(palette = "Set1")  
  theme_minimal(base_size = 16)  
  theme(axis.line = element_line(colour = "black", size = 0.24),
        aspect.ratio=4/5)

enter image description here

data:

structure(list(X = c("0 Months", "2 Months", "4 Months", "6 Months", 
"0 Months", "2 Months", "4 Months", "6 Months", "0 Months", "2 Months", 
"4 Months", "6 Months", "0 Months", "2 Months", "4 Months", "6 Months"
), y = c(100, 56.45161, 35.48387, 24.19355, 100, 80.76923, 61.53846, 
34.61538, 100, 53.06122, 44.89796, 24.4898, 100, 60, 48.57143, 
40), group = c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c", 
"c", "c", "d", "d", "d", "d")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15", "16"))
  • Related