带有 facet 的 ggplot 上混乱的注释文本

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

我想为

Fair
Good
添加“A”,为
Very good
Premium
添加“B”,为
Ideal
钻石添加“C”,但我的文字很混乱。

library(dplyr; ggplot2)

注释文本

ann_text <- expand.grid(
  x  = c(1.5, 3.5, 5),
  y     = 6000,
  label = c("A", "B", "C"),
  clarity = c("I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"),
  cut = LETTERS[4:10])
) 

点的虚拟 df

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = mean(price))

主线

diamonds %>%
ggplot() +
geom_bar(aes(x = cut, fill = clarity)) +
facet_wrap(~ color) +
ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
    scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) +
    geom_vline(xintercept=c(2, 4) + .5, lwd=.5, colour="black") +
  geom_text(data = ann_text, aes(x = x, y = y, label = label))  +
  scale_color_manual(name = "", label = "Average price", values = "black") 

感谢任何线索。

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

对于注释数据框,我想你不需要做

expand.grid
,每个标签一行就可以了。因此我使用
ann_text2
进行标签注释。以后如果你想避免标签重叠,使用
geom_text(check_overlap = TRUE)

library(dplyr)
library(ggplot2)

ann_text2 <- data.frame(x = c(1.5, 3.5, 5),
                        y = 6000,
                        label = LETTERS[1:3])

price.avg <- diamonds %>%
  group_by(cut, color) %>%
  summarise(price = mean(price))

diamonds %>%
  ggplot() +
  geom_bar(aes(x = cut, fill = clarity)) +
  facet_wrap(~ color) +
  ylab("Count") +
  xlab("Cut") + 
  geom_point(data = price.avg, aes(x = cut, y = price, col = "")) +
  scale_y_continuous(sec.axis = sec_axis(~. * 1, name = "price")) +
  geom_vline(xintercept=c(2, 4) + .5, lwd=.5, colour="black") +
  geom_text(data = ann_text2, aes(x = x, y = y, label = label), check_overlap = T)  +
  scale_color_manual(name = "", label = "Average price", values = "black") 

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