0

Would anyone know how to adjust the size of the left margin on a horizontal bar plot so long y-labels can be displayed properly? I have used base R, but if there's an easy fix in ggplot feel free to explain.

I have a data frame called NAV3 with the 55 y-labels that are the names of places (NowPort), and mean_boat_length for my values.

Below is the code with my attempt of adjusting the margins based on a solution from Automatic adjustment of margins in horizontal bar chart. It hasn't worked for my plot though :(

ylabs <- NAV3 %>%
  select("NowPort")

linch <- max(strwidth(ylabs, "inch") + 0.4, na.rm = T)

par(mai = c(1.02, linch, 0.82, 0.42))

barplot(height = NAV3$mean_boat_length, names = NAV3$NowPort,
  col = "#69b3a2",
  horiz = T, las = 1,
  xlab = "mean_boat_length")
    

This is the plot made from the above code This is a sample of my dataframe NAV3

CozyCat
  • 5
  • 2

2 Answers2

0

Here you have an alternative solution if you use ggplot. You just need to modify the left margin:

library(ggplot)

ggplot(data=df, aes(x=NAV3$mean_boat_length, y=NAV3$NowPort)) +
 geom_bar(stat="identity") +
 theme(
    plot.margin = margin(t = 0.5,  # Top margin
                         r = 1,    # Right margin
                         b = 0.5,  # Bottom margin
                         l = 2.5,  # Left margin
                         unit = "cm")
Isaac
  • 382
  • 2
  • 7
  • Wow! That worked! Thank you so much Isaac! :D How do I order the bars so they go smallest to largest? And how do I make the bars blue? – CozyCat Sep 13 '22 at 01:09
0

Here is an updated answer. It would be ideal if you can share a sample of the data. I hope this helps.

library(ggplot)

df$mean_boat_length <- factor(df$mean_boat_length, levels = df$mean_boat_length[order(df$NowPort)])

ggplot(data=df, aes(x=mean_boat_length, y=NowPort)) +
 geom_bar(stat="identity", color = "blue") +
 theme(
    plot.margin = margin(t = 0.5,  # Top margin
                         r = 1,    # Right margin
                         b = 0.5,  # Bottom margin
                         l = 2.5,  # Left margin
                         unit = "cm")
Isaac
  • 382
  • 2
  • 7
  • Thank you Isaac, I had a go with your code and got an error message that popped up after I tried running the factor levels line. The error read "Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [3] is duplicated" I don't understand what this means... I'll also add a subset of my data to my original post. – CozyCat Sep 13 '22 at 08:32