Belive
Belive

Reputation: 127

Labels are too long to fit into bar area

I used geom_text to put some text inside bar area, but I found that sometimes the text run off the bar area, see below. I want to make the text becomes a substring of the original text in the form that, substring = original_text[i:], where i is chosen automatically such that the substring can fit into the bar area. For example: if "ABCDEFGHIJKIFG" is too long to fit into the bar area, the text inside the bar are would be "JKIFG" for all bars. Graph Image

Initiate Dataframe

ordering <- c(1,2,1,2)
year <- c(2000,2000,2001,2001)
value <- c(1,10,2,10)
label <- c('ABCDEFGHIJKIFG','ABCDEFGHIJKIFG','ABCDEFGHIJKIFG','ABCDEFGHIJKIFG')
df <- data.frame("ordering" = ordering, "year" = year,'value' = value,'label' = label)

Plot Graph

library(ggstance)
library(ggplot2)
library(gganimate)

ggplot(df, aes(y = ordering, x = value)) +
  geom_barh(stat = "identity") +
  geom_text(aes(x = 0, label = paste(label, " ")), vjust = 0.2, hjust = 0,color='red') +
  transition_states(year, transition_length = 2, state_length = 0) +
  view_follow(fixed_y = TRUE)

Upvotes: 0

Views: 240

Answers (1)

Marius
Marius

Reputation: 60060

Here's a bit of a hack I thought up: if you make the plot background a fixed colour, you can plot a bar over the top of the text to cover it up. It's not perfect but it does keep the text from showing outside the bar:

max_val = max(df$value)
ggplot(df, aes(y = ordering, x = value)) +
    geom_barh(stat = "identity") +
    geom_text(aes(x = 0, label = label), vjust = 0.2, hjust = 0,color='red') +
    geom_rect(aes(xmin = value, xmax=max_val, ymin = ordering - 0.2, ymax = ordering + 0.2),
              fill = "#aaaaaa") +
    transition_states(year, transition_length = 2, state_length = 0) +
    view_follow(fixed_y = TRUE) +
    theme(panel.background = element_rect(fill = "#aaaaaa"),
          panel.grid = element_blank())

Hidden text


EDIT: After a bit more thinking, I came up with a version of this that gets closer to your original intent by having the label stick to the right hand side of the bar, and having the label disappear on the left hand side:

ggplot(df, aes(y = ordering, x = value)) +
    geom_barh(stat = "identity") +
    geom_text(aes(x = value, label = label), vjust = 0.2, hjust = 1, color='red') +
    geom_rect(aes(xmin = -2, xmax=0, ymin = ordering - 0.2, ymax = ordering + 0.2),
              fill = "grey92") +
    transition_states(year, transition_length = 2, state_length = 0) +
    # Manually setting limits, not ideal
    coord_cartesian(xlim = c(0, 10)) +
    theme(panel.background = element_rect(fill = "grey92"))

enter image description here

Upvotes: 1

Related Questions