0

I am making a barplot using ggpot2 and am deviding it to multiple plots with facet_wrap with scale = "free_y". I add labels to bars on each plot using geom_text. I want to increase each y axis by some % of the y_lim that is set automatically by free_y option in order to see all of the labels as some are now not inside the plot (in red squares in the picture).

plots

Here is the code I use to make the plot in the picture:

ggplot(random_df, aes(y = abs(amount), x = month, fill = ifelse(percent > 0, "green", "red"))) + 
  geom_col(aes(type = "Actual spent")) + 
  geom_line(aes(y = budget, x = month, group = Category, color = "Budget", type = "Budget")) +
  facet_wrap(~Category, ncol = 4, scales = "free_y") +
  scale_fill_manual(name = "Type", values = c("green" = "green", "red" = "red"), 
                    labels = c("Actual spent (positive)", "Actual spent (negative)")) +
  scale_color_manual(name = "Type", values = c("Budget" = "black"), labels = "Budget") +
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 90)) + 
  geom_text(aes(y = floor(abs(amount)), label = floor(abs(amount))), size = 3, angle = 90, hjust = -0.1)

And here is the code you can use to generate the data:

# Load required libraries
library(dplyr)
library(tidyr)

# Function to generate random values
generate_random_values <- function(n_rows) {
  tibble(
    Category = rep(paste0("Cat_", seq_len(n_rows/12)), each = 12),
    budget = runif(n_rows, 1000, 150000),
    amount = runif(n_rows, -150000, 0),
    percent = runif(n_rows, 0, 100),
    month = rep(month.abb, n_rows/12),
  )
}

# Create a random data frame with similar structure
random_df <- generate_random_values(n_rows = 240)

# Print the new data frame
print(random_df)

I have tried calcualting a new y_lim and adding it seperately but it does not work.

  • 1
    Please see this post: https://stackoverflow.com/questions/51735481/ggplot2-change-axis-limits-for-each-individual-facet-panel – Magnus Nordmo May 03 '23 at 10:45

1 Answers1

0

There is no avalibe solution for this problem yet, the workaround is using cowplot or gridExtra and making seperate plots.