使用富文本时,annotate() 会在 ggplot2 中的 geom_text() 上发生什么变化?

问题描述 投票:0回答:1

我有 2 个地块要连接在一起。顶部显示原始数据,第二个是主观评级。问题是,当我尝试使用 annotate() 和富文本解释评级的标签时,一切都会发生变化。但是,当我对常规文本使用 annotate() 时,我没有遇到这个问题。但是,在我的实际用例中,我需要富文本,因为我需要标签具有多种颜色。有多个 annotates() 每个都有自己的颜色是不守规矩的,因为文本很容易移动。

为什么会发生这种情况?有办法解决吗?我希望情节看起来像第二张图片,但颜色有快有慢。

library(ggplot2)
library(ggtext)
library(dplyr)
library(patchwork)

#sample data; basic tidying to resemble my real data, no help needed here
car_data <- mtcars %>%
  mutate(gear_fct = factor(gear), ordered = is.ordered(gear)) %>%
  group_by(gear_fct) %>%
  dplyr::summarize(avg_hp = mean(hp)) %>%
  mutate(power = if_else(avg_hp >= 100, "Fast", "Slow"))


#make base plot, no help needed here
plot <- car_data %>%
  ggplot(aes(x = gear_fct, y = avg_hp)) +
  geom_col()

  

#Make labels to go below the plot
table_plot <- ggplot(car_data, aes(x = gear_fct, y = 1)) +
  geom_text(aes(label = power), size = 2.5, fontface = "bold", nudge_x = 0) +
  annotate("richtext", label = "Rating<br>(<span style='color:#87B8C5;'>FAST</span> or <span style='color:#BD8A8B;'>SLOW</span>):",
           x = 0, y = 1,  size = 2, fontface = "bold", hjust = -.5,
           fill = NA, label.color = NA) +
  theme_void() +
  theme(axis.text.x = element_blank(), 
        axis.ticks.x = element_blank(),
        plot.margin = margin(0, 0, 0, 0))

#join plots together
combined_plot <- plot / table_plot + plot_layout(heights = c(3, 0.5))
combined_plot

该代码产生了这个图;请注意移动,并且评级不在轴下方。

enter image description here

但是,如果我用以下代码替换上面代码中的注释:

   annotate("text", label = "Rating\n(FAST or SLOW):", 
            x = .65, y = 1, size = 1, fontface = "bold") +

然后我得到了一个看起来完全符合我想要的效果的图,但是“快”和“慢”不是我需要的彩色:

enter image description here

r ggplot2 richtext geom-text annotate
1个回答
0
投票

添加

coord_cartesian(xlim = c(1, 3), clip = "off") +

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.