How do I show all values on the x-axis? In my example, I can only see Jan2021, July 2021, and Jan 2022 on my x-axis. I want to show all months from the "Month B" column.
Side question: What is the best method of handling column names with spaces in them?
Most of the time, using `Column Name` or as.name("Column Name") works, but sometimes I get an error when I use that.
library(tidyverse)
library(zoo) #for as.yearmon function
df3 <- structure(list(`Month B` = structure(c(2020.75, 2020.83333333333,
2020.91666666667, 2021, 2021.08333333333, 2021.16666666667, 2021.25,
2021.33333333333, 2021.41666666667, 2021.5, 2021.58333333333,
2021.66666666667, 2021.75, 2021.83333333333, 2021.91666666667,
2022, 2022.08333333333, 2022.16666666667), class = "yearmon"),
colA = c(777, 1111, 888, 999, 999, 1500, 1400, 1000, 1200,
999, 1200, 900, 1200, 1300, 777, 1200, 777, 900), colB = c(700,
800, 900, 700, 800, 900, 600, 500, 500, 600, 500, 500, 600,
111, 999, 999, 888, 777)), row.names = c(NA, -18L), class = c("tbl_df",
"tbl", "data.frame"))
df3$`Month B` <- as.yearmon(df3$`Month B`)
ggplot(df3, aes(`Month B`))
geom_line(aes(y = `colA`, colour = "colA"))
geom_line(aes(y = `colB`, colour = "colB"))
theme(axis.text.x = element_text(angle = 90)) ggtitle("MyTitle")
CodePudding user response:
Here is a suggestion:
Instead of yearmon()
I used here dmy
function from lubridate and applied it in ggplot with scale_x_date
:
library(lubridate)
library(tidyverse)
df3 %>%
mutate(`Month B`=dmy(paste("01", as.character(`Month B`)))) %>%
ggplot(aes(`Month B`))
geom_line(aes(y = `colA`, colour = "colA"))
geom_line(aes(y = `colB`, colour = "colB"))
scale_x_date(date_labels="%b %y",date_breaks ="1 month")
theme(axis.text.x = element_text(angle = 90)) ggtitle("MyTitle")