如何解决在ggplot中的geom_label_repel中合并文本和图像
我正在尝试绘制折线图,并用文本和图像的组合标记每个系列的最后一点。我通常为此使用ggrepel
软件包,并且仅使用文本就可以做到这一点。我的问题是我不知道如何在标签中添加图片。
我认为像Country <img src='https://link.com/to/flag.png' width='20'/>
这样的标签会起作用,所以这就是我尝试做的事情:
library(dplyr)
library(ggplot2)
library(ggrepel)
# example df
df <- data.frame(
Country = c(rep("France",5),rep("United Kingdom",5)),Ratio = rnorm(10),Days = c(seq(1,5,1),seq(4,8,1)),abbr = c(rep("FR",rep("GB",5))) %>%
group_by(Country) %>%
# add "label" only to last point of the graph
mutate(label = if_else(Days == max(Days),# combine text and img of country's flag
true = paste0(Country," <img src='https://raw.githubusercontent.com/behdad/region-flags/gh-pages/png/",abbr,".png' width='20'/>"),false = NA_character_)
)
# line graph
ggplot(data = df,aes(x = Days,y = Ratio,color = Country)) +
geom_line(size = 1) +
theme(legend.position = "none") +
geom_label_repel(aes(label = label),nudge_x = 1,na.rm = T)
这显然不是走的路,任何人都可以帮我吗?
解决方法
使用ggtext
函数geom_richtext()
尝试这种方法。您可以根据需要自定义其他元素。这里的代码:
library(dplyr)
library(ggplot2)
library(ggrepel)
library(ggtext)
# example df
df <- data.frame(
Country = c(rep("France",5),rep("United Kingdom",5)),Ratio = rnorm(10),Days = c(seq(1,5,1),seq(4,8,1)),abbr = c(rep("FR",rep("GB",5))) %>%
group_by(Country) %>%
# add "label" only to last point of the graph
mutate(label = if_else(Days == max(Days),# combine text and img of country's flag
true = paste0(Country," <img src='https://raw.githubusercontent.com/behdad/region-flags/gh-pages/png/",abbr,".png' width='20'/>"),false = NA_character_)
)
# line graph
ggplot(data = df,aes(x = Days,y = Ratio,color = Country,label = label)) +
geom_line(size = 1) +
theme(legend.position = "none") +
geom_richtext(na.rm = T,nudge_x = -0.1,nudge_y = -0.1)
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。