如何在ggplot中突出显示与特定文本匹配的geom_text

3

我希望在ggplot散点图中突出显示某个文本。这是我的代码:

library(ggplot2)

labels <- c("green", "blue", "orange", "blue", "green","red","purple","black")
num_1 <- c(1,2,3,4,5,6,7,8)
num_2 <- c(5,9,3,7,4,3,1,8)
df <- data.frame(labels,num_1,num_2)

p <- ggplot(df, aes(num_1,num_2,label=labels)) + geom_text() 
p


例如,我想通过将字体加粗或将颜色更改为黄色来突出显示“green”文本。两种方法都可以,但我一直无法使其正常工作。我尝试使用gghighlight,但没有找到使其正常工作的方法。
1个回答

5
你提供的三种建议都可行。使用gghighlight,你需要设置一个谓词来确定要突出显示的数据点:
library(ggplot2)

labels <- c("green", "blue", "orange", "blue", "green","red","purple","black")
num_1 <- c(1,2,3,4,5,6,7,8)
num_2 <- c(5,9,3,7,4,3,1,8)
df <- data.frame(labels,num_1,num_2)

ggplot(df, aes(num_1,num_2,label=labels)) + 
  geom_text() +
  gghighlight::gghighlight(labels == "green")
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...

如果您想使用原始的ggplot2,您可以在函数中简单地使用ifelse()

ggplot(df, aes(num_1, num_2, label= labels)) +
  geom_text(aes(fontface = ifelse(labels == "green", "bold", "plain")))

如果你想直接设置颜色,而不是先将它们映射到一个比例尺上,你可以使用I()函数来使用恒等比例尺,该比例尺不会映射/转换数据。

ggplot(df, aes(num_1, num_2, label= labels)) +
  geom_text(aes(colour = I(ifelse(labels == "green", "yellow", "black"))))

此内容创建于2021年4月16日,使用reprex包(v1.0.0)生成。


1
多有趣啊,把“绿色”涂成黄色... ;)(我知道这是原帖的要求)+1 - tjebo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接