rvisualization

Base R barplot: legends showing over the bars and bars are out of the x-axis scale


What goes wrong in this barplot code? The variable names go over the bars and the bars are out of the x-axis scale on the left.

df <- data.frame(
  x1 = 5.1,
  x2 = 5.5,
  x3 = 5.2
)

names(df) <- c('word word word word word',
               'word word',
               'word word word word')

df_long <- df %>% pivot_longer(cols = everything())


barplot(height=df_long$value, names=df_long$name, 
        col="#69b3a2",
        horiz=T, las=1,
        xlim = c(1,7))

enter image description here


Solution

  • The problem is that the barbplots want to start at 0 but you set the limits for the x-axis as xlim = c(1,7). This will work:

    df <- data.frame(
      x1 = 5.1,
      x2 = 5.5,
      x3 = 5.2
    )
    
    names(df) <- c('word word word word word',
                   'word word',
                   'word word word word')
    
    df_long <- df %>% pivot_longer(cols = everything())
    
    
    barplot(height=df_long$value, names=df_long$name, 
            col="#69b3a2",
            horiz=T, las=1,
            xlim = c(0,7))
    

    enter image description here

    EDIT: I found setting the argument xpd = FALSE within the barplot() funtion cuts off the tail of the barplot. Maybe this helps?

    barplot(height=df_long$value, names=df_long$name, 
            col="#69b3a2",
            horiz=T, las=1,
            xpd = FALSE,
            xlim = c(1,7))
    

    enter image description here