微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在ggplot中的geom_label_repel中合并文本和图像

如何解决在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)

但这会产生原始标签,而不是按预期方式带有国旗的国家名称

enter image description here

这显然不是走的路,任何人都可以帮我吗?

解决方法

使用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)

输出:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?