【问题标题】:Reorder geom_path lines to match factor level order重新排序 geom_path 行以匹配因子级别顺序
【发布时间】:2020-09-09 02:21:48
【问题描述】:

我想绘制三个项目在三个月内的动物计数总和(“总和”),通过 geom_points 连接到 geom_paths。

我已通过手动排序“月份”因子的级别来指定 x 轴的顺序。

如何重新排序geom_path 以遵循 x 轴的新顺序并平滑连接点?

library(dplyr)
library(ggplot2)

df <- data.frame("Project" = c("Cass River", "Cass River", "Cass River", "Godley River", "Godley River", "Godley River", "Tasman River", "Tasman River", "Tasman River"), 
                 "Month" = c("2019_Apr", "2019_Mar", "2019_May","2019_Mar", "2019_Apr", "2019_May", "2019_Mar", "2019_Apr", "2019_May"), 
                 "Sum" = as.integer(c("66", "3", "42", "0", "23", "7", "18", "70", "12")))

#Set the order of the months
df <- df %>% mutate(Month = factor(Month, levels = c("2019_Mar", "2019_Apr", "2019_May")))

df %>% 
  ggplot(aes(x = Month, y = Sum, group = Project)) +
     geom_point(aes(color = Project))+
     geom_path(aes(color = Project))+
     theme_classic() +
     theme(axis.text.x = element_text(angle = 90)) +
     xlab("\nDate") + 
     ylab("Total number of hedgehogs")

【问题讨论】:

  • 我怀疑你想要geom_line 而不是geom_path。另外,考虑将df$Sum 转换为整数/数字。
  • 是的,已经完成了,谢谢!我将编辑问题,因为df$Sum 是我原始数据中的一个整数。

标签: r ggplot2


【解决方案1】:

我不确定您的预期结果,以及您为什么使用geom_path。此外,您的原始数据和代码无法在我的机器上重现 OP 中的图形。

我们为x 轴使用数字变量可能会有所帮助。我用zoo::as.yearmon()。正如@Z.Lin 所建议的,我还将geom_path 替换为geom_line。如果这没有帮助,请告诉我,我会删除它。

library(zoo)
df$Month <- as.yearmon(str_replace(df$Month, "_", "-"), "%Y-%B")

df %>% 
  ggplot(aes(x = Month, y = Sum, color = Project)) +
  geom_point()+
  geom_line() + 
#  geom_path(aes(color = Project))+
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90)) +
  xlab("\nDate") + 
  ylab("Total number of hedgehogs")

【讨论】:

  • 这很有帮助,谢谢。我没有必要更改为年月格式,但 geom_line 更改成功了。我最初对geom_line 没有运气所以使用geom_path 尽管我承认我不知道何时使用其中一个。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 2020-03-07
  • 1970-01-01
  • 2016-12-14
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多