簡體   English   中英

R ggplot2 | 繪制方向方向的 Lat Long 坐標數據和軸中的 ID

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM