1

I am trying to create a bar chart within a shiny context. Everything looks good but the labels. As you can see in the below image, some of the labels are hidden behind the top horizontal line.

enter image description here

    Diff_plot <- reactive({
    ggplot(Diff_data(), aes(x =Difficulty_Type, y = Percentage, fill=County.y)) + geom_bar(stat =
                                                                       "identity",
                                                                       position = position_dodge()
             ) +

      scale_fill_manual(values=cbbPalette)+

      geom_text(
        aes(label = Percentage2),
        vjust = 0,
        colour = "black", 
        position = position_dodge(width=0.9),
        fontface = "bold",
        size=4,
        angle = 90,
        hjust = 0
      ) + 
      labs(
        x = "",
        y = "Frequecny",

        face = "bold"
      ) +
      theme_bw() + scale_y_continuous(labels = scales::comma) +
      theme(plot.title = element_text(
        hjust = 0.5,
        size = 15,
        colour = "Black",
        face = "bold"
      )
user213544
  • 2,046
  • 3
  • 22
  • 52
Nader Mehri
  • 514
  • 1
  • 5
  • 21

1 Answers1

1

you can use a combination of hjust and vjust to set the text on top of your bargraph.

Using hjust = -1, you will get more space between the top of your bargraph and the text. If your text is hidden by the top horizontal line, you can increase limits of y axis by using ylim

df <- data.frame(X = LETTERS[1:3],
                 Y = sample(1:10,3),
                 labels = letters[4:6])

library(ggplot2)
ggplot(df,aes(x = X, y = Y, label = labels))+
  geom_col()+
  geom_text(angle = 90, hjust = -1, vjust = 0.5)+
  ylim(0,6.5)

enter image description here

dc37
  • 15,840
  • 4
  • 15
  • 32
  • Thanks. Is there any way to define the ylim as a function of the maximum of y values plus some constant value. Something like this: ylim (0, Max Y+5). Also, I was wondering if I can combine this statement with your proposed one: scale_y_continuous(labels = scales::comma) – Nader Mehri Mar 04 '20 at 00:22
  • Sure, in `scale_y_continuous`, you can add the argument `limits` which is the same thing than `ylim`. You could define y limits by for example: `limits = c(0, max(df$y)*0.5)`. Does it answer your question ? – dc37 Mar 04 '20 at 00:26
  • 1
    In `scale_y_continuous` you can also use `expand` option. That would add some padding around the data. – Ben Mar 04 '20 at 01:05
  • Thank you both. I added limits = c(0, max(df$y)*0.5) to my syntax and got an error. Also, tried limits = c(0, 1) but got the error: nonnumeric argument to binary operator. – Nader Mehri Mar 04 '20 at 02:28
  • Can you edit your question to add a reproducible example of your dataset in order we can test it ? Such as `dput(NameofYourDataframe)` (see here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – dc37 Mar 04 '20 at 03:26