【问题标题】:R ggplot2 | Plotting direction-wise Lat Long coordinate data and IDs in axisR ggplot2 |在轴中绘制方向方向的经纬度坐标数据和 ID
【发布时间】:2021-10-08 09:37:17
【问题描述】:

当包含 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,从东端开始分别为 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 模式——如下所示:

这是我对上述情节的尝试:

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。因此,也许编写一个函数会是一种更有效的方法。我能想出的只是一个伪代码,但可能有更简单的方法来解决这个问题?

getDirectionalLevels <- function(test_df, direction){
    grab(Lat, Long) %>% 
        mutate(id_direction = sort(direction)) %>% 
        mutate(ID = factor(ID, levels = id_direction))
}

【问题讨论】:

  • 下面的代码解决了你的问题吗?如果它不适合你,请告诉我!
  • 是的,它适用于东西走廊,但对于南北走廊,我想我必须按照 Lat 值对 ID 进行排序。就像我在原帖中提到的那样,这里的函数可能会更好......如果(Long 极值的差异 > Lat 极值的差异),则沿着 Long 排序——这意味着走廊是东西向的,如果值是沿着 Lat (纬度差 > 经度差)——表示走廊是南北向。

标签: r function ggplot2 coordinates axis


【解决方案1】:
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))

两者都返回:

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多