I는 다른 부분의 색하고자 sf
의 변수를 사용하여 스트링을 ggplot
하고 geom_sf
. 를 사용하여 비슷한 작업을 수행 할 수 geom_path
있지만 geom_sf
비슷한 접근 방식에서는 작동하지 않는 것 같습니다. 누군가 가능한 접근 방식을 제공 할 수 있습니까?
샘플 데이터
library(sf)
library(ggplot2)
library(dplyr)
library(tibble)
df <- tibble(time = seq(1,21),
lon = seq(-50,-30, 1) + rnorm(n = 21),
lat = seq(10, 20, 0.5) + rnorm(n = 21),
type = c(rep('A',5),rep('B',10), rep('A',6)))
tibble / dataframe 사용 :
tibble 및 기본 ggplot을 사용하여이 작업을 수행 할 수 있습니다. 통합 group = 1
하면 단일 선이 type
. 이것은 내가 만들고 싶은 플롯 유형이지만 sf
대신 객체를 사용합니다.
ggplot() +
geom_path(data = df,
aes(lon, lat, color = type, group = 1))
사용 sf
목적 / 선 스트링을
내가 선 스트링으로 캐스팅하는 경우를 사용 group_by
하고 type
난 두 개의 선 스트링으로 끝날
df_sf <- st_as_sf(df, coords = c('lon','lat')) %>%
st_set_crs(.,value = 4326) %>%
group_by(type) %>%
summarize(do_union = TRUE) %>%
st_cast(.,'LINESTRING')
그런 다음 아래 코드에서 변형을 수행하면 두 개의 개별 줄이 생기고 유형 = A 인 두 부분이 연결됩니다.
ggplot() +
geom_sf(data = df_sf,
aes(color = type, group = 1))
접근 방식을 ggplot + geom_path()
사용하여 유형 동작 을 달성하는 방법이 있습니까 geom_sf()
(따라서 변수 등을 투영 할 수 있음)?
여기 에서 선을 세그먼트로 분할하는 접근 방식을 찾았 지만 사용 사례에는 과잉 일 수 있습니다.
이 시도:
df_sf <- df %>%
# ensure data is sorted along x-axis
arrange(lon) %>%
# detect each time type changes, & create a duplicate point with previous type
mutate(change.type = tidyr::replace_na(lag(type) != type, FALSE)) %>%
mutate(type = ifelse(change.type,
paste(lag(type), type, sep = ";"),
type) %>%
strsplit(";")) %>%
tidyr::unnest(cols = c(type)) %>%
# create new group column that increments with every colour change
mutate(change.type = tidyr::replace_na(lag(type) != type, FALSE)) %>%
mutate(new.type = cumsum(change.type)) %>%
st_as_sf(coords = c('lon', 'lat')) %>%
st_set_crs(., value = 4326) %>%
# group by both original type (for colour) & new type (for group)
group_by(type, new.type) %>%
summarize(do_union = TRUE) %>%
st_cast(.,'LINESTRING') %>%
ungroup()
결과 비교
cowplot::plot_grid(
ggplot() +
geom_path(data = arrange(df, lon),
aes(lon, lat, color = type, group = 1), size = 1) +
ggtitle("geom_path approach") +
theme(legend.position = "bottom"),
ggplot() +
geom_sf(data = df_sf,
aes(color = type, group = new.type), size = 1) +
ggtitle("geom_sf approach") +
theme(legend.position = "bottom"),
nrow = 1
)
데이터:
set.seed(123)
df <- tibble(time = seq(1,21),
lon = seq(-50,-30, 1) + rnorm(n = 21),
lat = seq(10, 20, 0.5) + rnorm(n = 21),
type = c(rep('A', 5), rep('B', 10), rep('A', 6)))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다