[英]R ggplot2 | Plotting direction-wise Lat Long coordinate data and IDs in axis
当包含week_days
的数据框绘制在 ggplot2 上或在表格中可视化时,工作日 go 在轴/表格上从左到右按字母顺序排列,从星期五开始。 这可以通过设置factor(week_days, levels= c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
手动配置。(可能有更好的我不知道的方式。)在沿轴以方向方式绘制包含纬度和经度的coordinate_IDs
时,我正在尝试找出类似的解决方案。
install.packages("pacman")
pacman::p_load(tidyverse, leaflet)
ID <- as.factor(as.character(1:9))
Lat <- as.numeric(c("33.55302", "33.55282", "33.55492", "33.55498", "33.55675", "33.55653", "33.55294", "33.55360", "33.55287"))
Long <- as.numeric(c("-112.0910", "-112.0741", "-112.0458", "-112.0459", "-112.0414", "-112.0420", "-112.0869", "-112.0526", "-112.0609"))
Value <- 11:19
test_df <- data.frame(ID, Lat, Long, Value)
levels(test_df$ID)
test_df %>%
leaflet() %>%
addTiles() %>%
addMarkers(., lng = Long, lat = Lat,
label = ~ID)
如您所见,最东端的 ID 是 5,最西端的 ID 是 1,从东边开始分别是 6、3、4、8、9、2 和 7。 此外,几对 ID 彼此非常接近。
test_df %>%
ggplot() +
geom_point(aes(x = ID, y = Value))
在ggplot2上绘制时,x轴go上东西方向的ID值从9到1。
但我希望它在轴上从右到左遵循 5、6、3、4、8、9、2、7、1 模式,就像这样:
这是我对上述 plot 的尝试:
test_df %>%
mutate(ID = factor(ID, levels = c("1","7","2","9","8","4","3","6","5"))) %>%
ggplot() +
geom_point(aes(x = ID, y = Value))
我不想通过在沿着走廊绘制 100 个 ID 时设置级别来手动执行此操作。 所以,也许写一个 function 会是一个更有效的方法。 我所能想到的只是一个伪代码,但可能有更简单的方法来解决这个问题?
getDirectionalLevels <- function(test_df, direction){
grab(Lat, Long) %>%
mutate(id_direction = sort(direction)) %>%
mutate(ID = factor(ID, levels = id_direction))
}
ID <- as.factor(as.character(1:9))
Lat <- as.numeric(c("33.55302", "33.55282", "33.55492", "33.55498", "33.55675", "33.55653", "33.55294", "33.55360", "33.55287"))
Long <- as.numeric(c("-112.0910", "-112.0741", "-112.0458", "-112.0459", "-112.0414", "-112.0420", "-112.0869", "-112.0526", "-112.0609"))
Value <- 11:19
test_df <- data.frame(ID, Lat, Long, Value)
似乎您想根据Long
值对ID
进行排序。
test_df %>%
mutate(ID = factor(ID, levels = test_df[order(test_df$Long), "ID"])) %>%
ggplot() +
geom_point(aes(x = ID, y = Value))
或者:
test_df %>%
mutate(ID = factor(ID, levels = test_df %>% arrange(Long) %>% select(ID) %>% unlist())) %>%
ggplot() +
geom_point(aes(x = ID, y = Value))
两者都返回:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.