gpt4 book ai didi

r - ggplot : re-order categorical y-axis (Gantt chart)

转载 作者:行者123 更新时间:2023-12-04 01:10:44 24 4
gpt4 key购买 nike

我正在尝试从具有不同任务(每个任务都有开始日期和结束日期)的表格中生成甘特图。

library(tidyverse)

# Sample data
df1 <- data.frame(from = c("2020-01-01", "2020-02-02", "2020-05-04", "2020-02-01", "2020-01-20", "2020-02-10"),
to = c("2020-03-30", "2020-03-15", "2020-05-20", "2020-04-05", "2020-03-05", "2020-04-13"),
task= c("Task 1", "Task 2", "Task 3", "Task 4", "Task 5", "Task 6"),
group = c("Finance", "Finance", "Research", "Research", "Other", "Other")
)

# Plot gantt-chart
df1 %>% mutate(from = as.Date(from),
to = as.Date(to)) %>%
pivot_longer(cols = c(from, to), values_to = "date") %>%
ggplot(aes(x=date, y=task, colour = group)) +
geom_line(lwd=3) +
geom_point(aes(color=group), alpha=.5, pch=18, size=5) +
scale_x_date(position="bottom", date_breaks = "1 week", date_labels="%U") +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5))+
ggtitle("Milestones") +
labs(y="", x = "", colour="Responsible")

到目前为止一切顺利,但现在我遇到了一个主要问题和一个小问题:

主要问题:

  • 如何重新排列 y 轴上的类别,因为它们出现在数据中(不是按字母顺序排列)?从上到下应该是:财务、研究、其他。此外,在每个类别(金融、研究、其他)中,行应按开始日期排序(即首先开始的任务应在最前面)

小问题:

  • 如何在 x 轴上为每个月画一条粗线,为每周画一条细线?

感谢您的帮助!

最佳答案

这可以这样实现:

  1. 正如@RuiBarrades 在他的评论中提到的那样,要获得正确的顺序,您必须转换为一个因子并以正确的顺序设置级别。首先,为组设置级别。其次,为了按所需顺序获取任务,我按组和开始日期重新排列数据集,并使用 forcats::fct_inorder 以所需顺序设置任务级别。

  2. 如果我没看错,您想要每周和每月使用不同的网格线吗?这可以通过设置 date_breaks_minor="month" 和通过 themepanel.grid.minor/major.x 设置网格线样式来实现.在这里,我选择了“黑色”颜色,但如果您喜欢不同的尺寸,可以通过 size 进行选择。

library(tidyverse)
library(ggplot2)

# Sample data
df1 <- data.frame(from = c("2020-01-01", "2020-02-02", "2020-05-04", "2020-02-01", "2020-01-20", "2020-02-10"),
to = c("2020-03-30", "2020-03-15", "2020-05-20", "2020-04-05", "2020-03-05", "2020-04-13"),
task= c("Task 1", "Task 2", "Task 3", "Task 4", "Task 5", "Task 6"),
group = c("Finance", "Finance", "Research", "Research", "Other", "Other")
)

# Plot gantt-chart
df1 %>% mutate(from = as.Date(from),
to = as.Date(to),
group = factor(group, levels = c("Finance", "Research", "Other"))) %>%
arrange(desc(group), desc(from)) %>%
mutate(task = forcats::fct_inorder(task)) %>%
pivot_longer(cols = c(from, to), values_to = "date") %>%
ggplot(aes(x=date, y=task, colour = group)) +
geom_line(lwd=3) +
geom_point(aes(color=group), alpha=.5, pch=18, size=5) +
scale_x_date(position="bottom", date_breaks = "1 week", date_minor_breaks = "1 month",
date_labels="%U") +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5),
panel.grid.minor.x = element_line(color = "black"))+
ggtitle("Milestones") +
labs(y="", x = "", colour="Responsible")

关于r - ggplot : re-order categorical y-axis (Gantt chart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64940870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com