I have created a data set and I am having some issues with graphing it. I think it stems from the fact that the data set is quite small so R doesn't recognise my X axis as years but rather as continuous data. Therefore, my graph has 2020.5. So, I have to convert the years column using as.factor(AshQuads$Year) but then it refuses to connect the years with geom_line
.
This is the code I have been using
ggplot(Ash_Quads, aes(x=Year, y=Quadrats, colour=factor(Ash)))
geom_point()
theme_bw()
I was wondering if anyone can help please?
CodePudding user response:
I would suggest just leaving the x-axis as continuous, rather than converting it to a factor. Simply provide the actual breaks you want for your x-axis, in this case, the years 2020:2022
ggplot(df, aes(Year,Quadrats,color=Ash))
geom_point() geom_line()
scale_x_continuous(breaks=2020:2022)
theme_bw()
CodePudding user response:
One option is to set the Year
to factor (as you mention), then add the group into aes
(i.e., group = Ash
). You also need to add geom_line
, which you don't have in your code.
library(tidyverse)
ggplot(Ash_Quads, aes(x = factor(Year), y = Quadrats, colour = factor(Ash), group = Ash))
geom_point()
geom_line()
theme_bw()
Or you can use scale_x_continuous
to set the x-axis (so leave as continuous data and not convert Year
to factor):
ggplot(Ash_Quads, aes(x = Year, y = Quadrats, colour = factor(Ash)))
geom_point()
geom_line()
scale_x_continuous(breaks = 2020:2022)
theme_bw()
Data
Ash_Quads <- structure(list(Year = c(2020, 2021, 2022, 2020, 2021, 2022),
Quadrats = c(37, 31, 13, 54, 56, 38), Ash = c("No Ash", "No Ash",
"No Ash", "Ash", "Ash", "Ash")), class = "data.frame", row.names = c(NA,
-6L))