R语言ggplot2中geom_line仅图例显示绘图区不展示问题求解
问题原因
你的问题核心是pivot_longer生成的year_range为字符类型,ggplot默认将其识别为离散型x轴,此时geom_line需要显式指定group参数才能识别同一分组内的点进行连线,未指定的情况下就会出现点正常显示、线条不显示但图例正常的情况。
解决方案
只需要在geom_line的美学映射中添加group = country1即可修复,修改后的代码如下:
plot1 <- dat1 %>% rename(country1 = "Region, subregion, country or area *", `1955` = "1950-1955", `1960` = "1955-1960", `1965` = "1960-1965", `1970` = "1965-1970", `1975` = "1970-1975", `1980` = "1975-1980", `1985` = "1980-1985", `1990` = "1985-1990", `1995` = "1990-1995", `2000` = "1995-2000", `2005` = "2000-2005", `2010` = "2005-2010", `2015` = "2010-2015", `2020` = "2015-2020") %>% mutate(difference = `2020` - `1955`) %>% mutate(hightfr = if_else(`2020` > 5, "high fertility", "fast decline")) %>% filter(`Parent code` %in% c(911, 913)) %>% filter(`2020` > 5 | `difference` < -3) %>% pivot_longer(8:21, names_to = "year_range", values_to = "tfr") %>% ggplot() + # 新增group参数指定按国家分组连线 geom_line(mapping = aes(year_range, tfr, color = `country1`, group = `country1`)) + geom_point(mapping = aes(year_range, tfr, color = `country1`, shape = `hightfr`)) plot1
可选优化
如果需要x轴呈现连续时间轴效果,可以将year_range转换为数值类型,示例如下:
# 在pivot_longer后新增一行转换代码 mutate(year = as.numeric(year_range))
之后将x轴映射换成year即可,无需额外指定group参数也可以正常连线。
内容的提问来源于stack exchange,提问作者Scott Hebert
相关产品推荐
相关产品推荐

