Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading