ixodid
ixodid

Reputation: 2400

Add offset label to ggplot histogram

I wish to add a label to one specific bar of a histogram, but off to the side, not above. Like this:

enter image description here

I'm unsure as to how to ONLY label the red bar nor how to offset the label with an arrow.

Code

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"))

Upvotes: 0

Views: 77

Answers (1)

Marius
Marius

Reputation: 60070

If this is just a one-off and you're OK specifying the label position manually, you can use 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")

Result:

plot with label + arrow

Upvotes: 2

Related Questions