将偏移标签添加到ggplot直方图

时间:2018-08-03 01:18:49

标签: r ggplot2

我希望在直方图的一个特定条上添加标签,但要在侧面而不是上方添加标签。像这样:

enter image description here

我不确定如何只标记红色条,也不知道如何用箭头偏移标签。

代码

library(tidyverse)

tree_df <- tibble (
  rank = c(1, 2, 3, 4, 5),
  name = c("oak", "elm", "maple", "pine", "spruce"),
  freq = c(300, 50, 20, 10, 5)
) 

bar_colour <- c(rep("black", 4), rep("red", 1))

last_bar <- tree_df[5,]

ggplot(data = tree_df, aes(x = reorder(row.names(tree_df), freq), y = freq)) +
  geom_col(fill = bar_colour) +
  geom_label(data = tree_df, label = c("Norway"))

1 个答案:

答案 0 :(得分:2)

如果这只是一次,您可以手动指定标签位置,则可以使用annotate

ggplot(data = tree_df, aes(x = reorder(row.names(tree_df), freq), y = freq)) +
    geom_col(fill = bar_colour) +
    annotate(geom = "segment", x = 4, xend = 4.5, y = 250, yend = 250, 
             arrow = arrow(length = unit(0.03, "npc"))) +
    annotate(geom = "label", x = 4, y = 250, label = "Norway")

结果:

plot with label + arrow