如何将甘特图(Gantt Chart)Y轴地点按字母顺序排序?
解决R语言甘特图Y轴地点按字母排序的问题
你尝试生成Y轴地点按字母顺序排列的甘特图但未成功,以下是针对你提供的代码和数据的解决方案:
要让ggplot的Y轴按字母排序,核心是把location列转换为因子类型并指定排序后的水平——因为ggplot对离散轴的排序依据是因子的水平顺序,而非数据框的行顺序(你之前用arrange只是调整了数据行的顺序,不影响轴的排序规则)。
修改后的完整代码
# 加载所需包 library(readxl) library(reshape2) library(dplyr) library(ggplot2) library(lubridate) # 使用你提供的数据子集测试(实际使用时替换为read_excel("2025-05-07_gantt_chart.xlsx")) gantt <- structure(list(location = c("Hebron GBS", "Hibernia GBS", "SeaRose FPSO", "bdv", "Holyrood Thermal Generating station", "bdv", "Soldier's pond", "bdv", "bdv", "bdv"), year = c("2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019", "2019"), `start date` = structure(c(1567296000, 1567296000, 1567296000, 1569369600, 1569801600, 1569974400, 1569974400, 1570233600, 1570406400, 1570665600), tzone = "UTC", class = c("POSIXct", "POSIXt")), `end date` = structure(c(1572480000, 1572480000, 1572480000, 1569715200, 1572393600, 1570060800, 1572393600, 1570320000, 1570492800, 1570752000), tzone = "UTC", class = c("POSIXct", "POSIXt")), ...5 = c("FALSE", "FALSE", "FALSE", "FALSE", "FALSE", "only 1 day", "FALSE", "only 1 day", "only 1 day", "only 1 day" )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame" )) # 生成row_id gantt$row_id <- seq(1,nrow(gantt)) # 处理日期并转换数据格式 mgantt <- melt(gantt, measure.vars = c("start date", "end date")) mgantt$yday <- yday(mgantt$value) # 关键步骤:按字母顺序排序地点,转换为因子 sorted_locations <- sort(unique(mgantt$location)) mgantt$location <- factor(mgantt$location, levels = sorted_locations) # 绘图 ggplot(mgantt, aes(x = yday, y = location, group = row_id)) + geom_line(linewidth = 4) + facet_wrap(~year) + labs(title = NULL, x = "Julian date", y = NULL) + theme(panel.grid.minor = element_line(colour="white", linewidth = 0.5), legend.position="right", plot.title = element_text(hjust = 0.5))
关键逻辑说明
sort(unique(mgantt$location)):提取所有不重复的地点名称,默认按字母升序排列(若需要降序,可添加参数decreasing = TRUE)factor(mgantt$location, levels = sorted_locations):将location列转换为因子类型,并强制指定水平顺序,ggplot绘图时会严格遵循该顺序渲染Y轴
内容的提问来源于stack exchange,提问作者Fiona
相关产品推荐
相关产品推荐

