當包含week_days在 ggplot2 上繪制或在表格中可視化的資料框時,作業日在軸/表格上按字母順序從左到右,從星期五開始。這可以通過設定手動配置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,從東邊的 ID 為 6、3、4、8、9、2 和 7。此外,幾對 ID 彼此非常接近。
test_df %>%
ggplot()
geom_point(aes(x = ID, y = Value))
在 ggplot2 上繪圖時,x 軸上的 ID 值沿東西方向從 9 變為 1。

但我希望它遵循軸上從右到左的 5, 6, 3, 4, 8, 9, 2, 7, 1 模式——像這樣:

Here's what I tried for the aforementioned 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))
I don't want to do this manually by setting the levels when plotting, say, 100 IDs along a corridor. So, perhaps writing a function would be a more efficient approach. All I could come up with is a pseudo-code, but there might be a much simpler way to approach this problem?
getDirectionalLevels <- function(test_df, direction){
grab(Lat, Long) %>%
mutate(id_direction = sort(direction)) %>%
mutate(ID = factor(ID, levels = id_direction))
}
uj5u.com熱心網友回復:
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)
看來,如果你想排序ID沿著Long價值。
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))
兩者都回傳:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315898.html
標籤:r function ggplot2 coordinates axis
下一篇:嵌套ggplot直方圖而不是累積
