我想對 x 軸進行排序以讀取 Jan - Dec。這是我的嘗試:
temp = structure(list(Month_Year = c("2021-01", "2021-02", "2021-03",
"2021-04", "2021-05", "2021-06", "2021-07", "2021-08", "2021-09",
"2021-10", "2021-11", "2021-12", "2022-01"), Percent = c(75,
100, 100, 98.6, 83.3, 83.3, 73.3, 83.3, 97.1, 93.1, 76.5, 100,
100), Year = c(2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021,
2021, 2021, 2021, 2021, 2022), MonthN = c(1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 1), Month = c("Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan")), class = "data.frame", row.names = 60:72)
ggplot(temp, aes(x = Month, y = Percent, group=Year, colour=factor(Year)))
geom_line()
geom_point()
labs(x="Month", colour="Year")
theme_classic()
uj5u.com熱心網友回復:
將您的月份列轉換為按正確順序設定水平的因子。在你的情況下,這可以很容易地用month.abb常數來實作。
library(ggplot2)
ggplot(temp, aes(x = factor(Month, levels = month.abb), y = Percent, group = Year, colour = factor(Year)))
geom_line()
geom_point()
labs(x = "Month", colour = "Year")
theme_classic()

- 第二種選擇是
Monnth按您的列重新排序您的MonthN列,即或reorder(Month, MonthN)。
uj5u.com熱心網友回復:
一種選擇是將Month_Year列從 acharacter轉換為真正的Date格式。這可以很容易地提取自動使用 {lubridate} 包的year、month和縮寫等month內容,如果您必須以這種方式注釋大型資料集,這可能會有所幫助。然后,您可以使用forcats::fct_reorder()將縮寫按正確的順序排列。
library(tidyverse)
library(lubridate)
d <- structure(list(Month_Year = c("2021-01", "2021-02", "2021-03", "2021-04", "2021-05", "2021-06", "2021-07", "2021-08", "2021-09", "2021-10", "2021-11", "2021-12", "2022-01"), Percent = c(75, 100, 100, 98.6, 83.3, 83.3, 73.3, 83.3, 97.1, 93.1, 76.5, 100, 100)), class = "data.frame", row.names = 60:72)
# extract month and year info directly from date
d %>%
mutate(date = ym(Month_Year),
year = year(date),
month = month(date),
month_abr = fct_reorder(month.abb[month], month)) %>%
ggplot(aes(x = month_abr, y = Percent, group = year, colour = factor(year)))
geom_line()
geom_point()
labs(x = "Month", colour = "Year")
theme_classic()

由reprex 包于 2022-04-08 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/457871.html
