使用GGPLOT自动为图例添加标签值

问题描述 投票:1回答:1

我是这个论坛的新手,所以如果我不遵守某些规则,请事先向我道歉。

我正在基于不同的变量创建许多相似的地图。到目前为止,手动编辑图例标签已经花费了很多时间,所以我想知道是否有更简单的方法可以自动进行图例标签而无需手动编辑。为了说明我的观点,我使用库(usmap)中提供的美国地震数据。这是usmap中的公开可用数据。

library(usmap)

eq_transformed <- usmap_transform(earthquakes)
# say I want to transform the variable mag to a quartile, and map based on the quartile. note this is not my real data, so the map below will look weird

library(dvmisc)
eq_transformed$magqt<-quant_groups(eq_transformed$mag,4)
table(eq_transformed$magqt)
#the quartiles are
#[2.5,2.67] (2.67,2.9] (2.9,3.33] (3.33,7.1]  
# 591        545        562        556       

ggplot()+
  geom_point(data=eq_transformed, aes(x=lon.1, y=lat.1,fill=magqt))+
  theme_void()+
  scale_fill_manual( values=c("black", "blue", "grey","red"),
                     #here I need to manually input quartile thresholds based on the output, and also need to change it to percentage form
                     labels=c("2.5%-2.67%","2.68%-2.9%","2.91%-3.33%","3.34%-7.1%"))+
  theme(legend.position=c(0.8,0.85), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "black"))

是否有一种方法可以使图例保持原样,而不必手动输入值?我认为唯一有用的功能是mutate paste0。但是我不知道如何使其在刻度范围内与标签功能一起使用。

任何建议,不胜感激!

r ggplot2 label
1个回答
0
投票

此代码应该可以正常工作

library(usmap)

eq_transformed <- usmap_transform(earthquakes)

library(dvmisc)
eq_transformed$magqt<-quant_groups(eq_transformed$mag,4)

str_c_dash <- partial(str_c,sep = " - ") # just a helper to use anonymous functions lates

eq_transformed2 <- eq_transformed %>% 
  mutate(magqt = magqt %>%
           as.character() %>% 
           str_extract("[:digit:]{1}\\.[:digit:]{1,2},[:digit:]{1}\\.[:digit:]{1,2}") %>% # regex to capture the %s
           str_split(pattern = ",") %>% # the pattern seem separating the quantiles before
           map(str_c,"%") %>%  # combine the strings with the percent sign
           map_chr(.f = ~ reduce(.x,.f = str_c_dash)) # reduce upper and lower bound with a " - "
         )



library(tidyverse)
ggplot()+
  geom_point(data=eq_transformed2, aes(x=lon.1, y=lat.1,fill=magqt))+
  theme_void()+
  scale_fill_manual( values=c("black", "blue", "grey","red"))+
  theme(legend.position=c(0.8,0.85), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "black"))
© www.soinside.com 2019 - 2024. All rights reserved.