1
votes

I am using a dataset to create a horizontal in the horizontal orientation. Something similar to what has been proposed as a solution in R: How can I make a barplot with labels parallel (horizontal) to bars.

However, the number of labels in the Y axis of my horizontal barplot chart are a little too many (due to the problem in hand) and hence, they are overlapping over each other.

Is there a way to preserve the barplot bin size and show a subset of the Y labels in the horizontal orientation of the barplot?

thanks, rajat

1

1 Answers

1
votes

Here's one way to do it, we can use a nice solution to interleave the names from your data with blanks:

generate some data

set.seed(123)
df1 <- data.frame(x = replicate(50, paste(sample(letters, 2, replace = T), collapse = '')),
                  y = sample(1:10, 50, replace = T), stringsAsFactors = FALSE)

make a barplot, using a subset of the names

barplot(df1$y, names.arg = c(rbind(df1$x, rep('', 50)))[1:50], horiz = T, las = 1)

The main trick is the names.arg = c(rbind(df1$x, rep('',50)))[1:50] line. It interleaves blanks between the names from the data. Effectively, we are replacing half of the names with blank space.

If that's not sufficient, we can define a function which takes in a vector of names, x, and a multiple, m that defines which values to replace with blanks:

replace_multiple <- function(x, m){
    len_x <- length(x)
    index_to_replace <- seq(1, len_x, by = m)
    x[index_to_replace] <- ''
    return(x)
}

replace_multiple(letters[1:12], m = 2)
# ""  "b" ""  "d" ""  "f" ""  "h" ""  "j" ""  "l"
replace_multiple(letters[1:12], m = 3)
# ""  "b" "c" ""  "e" "f" ""  "h" "i" ""  "k" "l"
replace_multiple(letters[1:12], m = 4)
# ""  "b" "c" "d" ""  "f" "g" "h" ""  "j" "k" "l"