r - 根据数据集中的列对图中的分面进行排序

标签 r ggplot2 facet facet-grid

所以,我有一个看起来像 this 的数据集.

我的任务是创建一个平滑的多面可视化,显示每个珊瑚在每个地点的漂白率,我已经成功地做到了,就像这样:

(我完全意识到这段代码可能很糟糕并且其中有一些错误,如果有人能告诉我改进它或纠正其中一些严重错误的方法,我将不胜感激。

coral_data <- read.csv("file.csv")

#options(warn=-1)

library(ggplot2)

ggplot(coral_data, aes(x=year, y=value, colour=coralType, group=coralType)) +
  geom_smooth(method="lm", se=F) +
  scale_x_continuous(name="Year", breaks=c(2010, 2013, 2016)) + 
  scale_y_discrete(breaks = seq(0, 100, by = 10)) +
  facet_grid(coralType ~ location, scales="free")+
  expand_limits(y=0) +
  labs(x="\nBleaching Rate", y="Year", title="Coral Bleaching for different corals at different sites over the years\n")

enter image description here

但是,我还必须按纬度对分面进行排序(目前,它类似于 site01、site02 等,但我希望分面网站按其纬度值排序,无论是升序还是降序)但遗憾的是我不知道至于我将如何做到这一点。

因此,有人可以告诉我该怎么做吗?

最佳答案

考虑按 latitude 对数据框进行排序,然后通过使用 unique 将其级别定义为新排序来重新分配 location 因子变量:

# ORDER DATA FRAME BY ASCENDING LATITUDE
coral_data <- with(coral_data, coral_data[order(latitude),])    
# ORDER DATA FRAME BY DESCENDING LATITUDE
coral_data <- with(coral_data, coral_data[order(rev(latitude)),])

# ASSIGN site AS FACTOR WITH DEFINED LEVELS
coral_data$location <- with(coral_data, factor(as.character(location), levels = unique(location)))

ggplot(coral_data, ...)

关于r - 根据数据集中的列对图中的分面进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61427635/

相关文章:

r - 在 sprintf 中使用百分号 (%)

r - 将有关轴上变量的更多信息合并到 ggplot 中的热图中

r - ggplot 从 csv 文件创建多线图

r - Base R 有没有办法复制 Excel 中的 VLOOKUP TRUE 的功能?

r - R 中使用 Twitter Streaming API 进行 Oauth(使用 RCurl)

r - 使用 ggplot2 绘制 fitdist 图

r - 基于条件的部分粗体ggplot2指南标签

r - 像在facet_grid中一样在facet_wrap中设置 “space”

python - 为 plotly 人物的每个方面添加痕迹

plotly - 在 Plotly 中使用面网格上的条形图和平均线