'R:How can use ggplot2 order month x axis
My data like this,but draw plot x axis is 12_01 12_10 12_11 12_12 12_2 I want to like 12_01 12_02 12_03...... 12_12 How can do it? thanks!
df=data.frame(year=12,
month=1:12,
g=c(10,20,14,15,11:18))
df2 <- df %>%
arrange(month) %>%
unite(year_month,year,month) %>%
group_by(year_month)
ggplot(df2 , aes(x = year_month, y =g,group = 1))+
geom_line() +
geom_point(shape = 22, size = 2, fill = "white")
Solution 1:[1]
You could manage this by converting year_month into a factor; or alternatively using {lubridate}...
library(dplyr)
library(tidyr)
library(ggplot2)
library(stringr)
df=data.frame(year=12,
month=1:12,
g=c(10,20,14,15,11:18))
df2 <- df %>%
arrange(month) %>%
unite(year_month,year,month) %>%
mutate(year_month = factor(year_month, levels = paste0("12_", 1:12))) %>%
group_by(year_month)
ggplot(df2 , aes(x = year_month, y =g,group = 1))+
geom_line() +
geom_point(shape = 22, size = 2, fill = "white")
Alternatively with lubridate if you want to preserve the variable as a date object:
df2 <- df %>%
arrange(month) %>%
unite(year_month,year,month) %>%
mutate(year_month = ym(year_month)) %>%
group_by(year_month)
ggplot(df2 , aes(x = year_month, y =g,group = 1))+
geom_line() +
geom_point(shape = 22, size = 2, fill = "white")+
scale_x_date(date_labels = "%y_%m",
date_breaks = "1 month")

Created on 2022-03-18 by the reprex package (v2.0.1)
Solution 2:[2]
Why not make them into actual dates?
df %>%
arrange(month) %>%
mutate(date = as.Date(paste(paste0(20, year), month, 1, sep = '-'))) %>%
ggplot(aes(x = date, y =g,group = 1))+
geom_line() +
geom_point(shape = 22, size = 2, fill = "white")
Solution 3:[3]
My recommdation is to create a date variable in you dataframe and use that in the x axis, that way is more flexible de axis label configuration, via scale_x_date().
Look at two options:
library(dplyr)
library(ggplot2)
library(lubridate)
df <- data.frame(year = 12, month = 1:12, g = c(10, 20, 14, 15 , 11:18))
df2 <- df %>%
mutate(
date = make_date(year + 2000, month, "01")
)
ggplot(df2, aes(x = date, y = g)) +
geom_line() +
geom_point(shape = 22, size = 2, fill = "white") +
scale_x_date(labels = ~format(., '%m_%y'))

ggplot(df2, aes(x = date, y = g)) +
geom_line() +
geom_point(shape = 22, size = 2, fill = "white") +
scale_x_date(labels = ~format(., '%b %y'))

Created on 2022-03-18 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Allan Cameron |
| Solution 3 | Johan Rosa |

