jha*_*oo8 3 r data-visualization ggplot2
我想突出显示 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
Run Code Online (Sandbox Code Playgroud)
例如,我想通过将其字体更改为粗体或将其颜色更改为黄色来突出显示文本“绿色”。两者都有效,但我无法让它发挥作用。我尝试过使用 gghighlight 但还没有找到让它工作的方法。
您的所有三个建议都有效。使用 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...
Run Code Online (Sandbox Code Playgroud)

如果你想留在普通的 ggplot2 中,你可以简单地ifelse()在aes()函数中使用 an :
ggplot(df, aes(num_1, num_2, label= labels)) +
geom_text(aes(fontface = ifelse(labels == "green", "bold", "plain")))
Run Code Online (Sandbox Code Playgroud)

如果您想直接设置颜色,而不先将它们映射到比例,则可以使用该I()函数来使用不映射/转换数据的标识比例。
ggplot(df, aes(num_1, num_2, label= labels)) +
geom_text(aes(colour = I(ifelse(labels == "green", "yellow", "black"))))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v1.0.0)于 2021-04-16 创建