timeywimey
timeywimey

Reputation: 41

How to remove excess lines in ggplot

I'm looking at growth My dataset (of averages) looks like this - values are growth rates

enter image description here

However for some reason when I add the geom_plot function I get extra lines (see photo below)

Just wondering if anyone knows why this may be and how I could fix it

July<- aggregate(Growth$July, by = list(Growth$Site), FUN= mean)
August<- aggregate(Growth$August, by = list(Growth$Site),FUN=mean)
September<- aggregate(Growth$September, by = list(Growth$Site), FUN=mean)

Growthplot <- cbind(July, August, September)
Growthplot <- Growthplot[-c(3,5)]
names(Growthplot) <- c("Site", "July","August", "September")
Growthplotlong <- Growthplot %>%
  pivot_longer(
    cols = c(starts_with('July'), starts_with('August'), starts_with('September')),
    names_to = "Month", values_to = "Length")#turns data from wide to long 

growth_df <- data.frame(x = Growthplotlong$Month, y = Growthplotlong$Length, group = Growthplotlong$Site)
plot(growth_df)


ggplot(growth_df, aes(x = Growthplotlong$Month, y = Growthplotlong$Length,colour=as.factor(group))) +
  geom_point(aes(colour = group, group=1)) +
  geom_path(aes(colour = group, group=1))+# Points and color by group
  scale_color_discrete("Site") +# Change legend title
  xlab("Month") +              # X-axis label
  ylab("Growth in cm")  +  
  scale_x_discrete(limits = c("July","August","September"))+
  theme(axis.line = element_line(colour = "black", # Changes the default theme
                                 size = 0.24))

enter image description here

Upvotes: 0

Views: 97

Answers (1)

stefan
stefan

Reputation: 125697

The issue is simply that you are using geom_path which will connect the starting and the end point. To fix this, switch to geom_line. Additionally I simplified your code a bit:

Note: As a general rule don't use something like x=Growthplotlong$Month. Simply do x=Month to specify the column you want to map on an aesthetic.

Growthplot <- data.frame(
  Site = letters[1:4],
  July = 0,
  August = c(1, 3, -1, 1),
  September = c(2, 4, 2, 5)
)

library(ggplot2)
library(tidyr)
library(dplyr)

growth_df <- Growthplot %>%
  pivot_longer(-Site, names_to = "Month", values_to = "Length") %>%
  mutate(Month = factor(Month, levels = c("July", "August", "September")))

ggplot(growth_df, aes(x = Month, y = Length, colour = Site, group = Site)) +
  geom_point() +
  geom_line()+
  labs(color = "Site", x = "Month", y = "Growth in cm")  +  
  theme(axis.line = element_line(colour = "black", size = 0.24))

Upvotes: 3

Related Questions