1

I'm trying to make a plot with a very specific theme and background.

How can I add horizontal lines to a ggplot2 plot background/theme, but only at the positions where the y-axis has numbers in the tick mark position?

For example, consider the following plot. I only want the background theme to have a horizontal line on the y-axis when there are numeric labels on the y-axis. That is at the values 0, 500, 1000, 1500. Elsewise, no horizontal line on the background theme.

enter image description here

Here is the reproducible code:

# Load the ggplot2 library

library(ggplot2)

# Create a data frame with some made-up data

sales <- data.frame(
  month = c("January", "February", "March", "April", "May"),
  sales = c(500, 750, 1000, 1250, 1500),
  region = c("North", "South", "East", "West", "Central")
  
)

#Add plot
ggplot(sales, aes(x = month,  y =sales, fill = region, alpha = .001 )) +
  geom_bar(stat = "identity") +
  labs(x = "Month", y = "Sales", title = "Monthly Sales") +
  theme_minimal() +
  theme(legend.position = "top",
        legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5),
        plot.caption= element_text(hjust = 0),
        # axis.title.y=element_blank(),
        panel.grid.major.x = element_blank(),
        legend.key.size = unit(.75, "lines"),
        legend.text = element_text(size = rel(1)),
        text = element_text(color = "black"),
        plot.background = element_rect(fill = 'white', color = 'white'))

Thank you

Sharif Amlani
  • 1,138
  • 1
  • 11
  • 25
  • One comment: your "alpha = 0.001" parameter isn't currently doing what it should be because it's being passed to the aes() argument instead of the geom_bar() argument. That's why you've got the 0.001 in the legend and it looks like your bars are more of a alpha=0.5 instead of 0.001 (practically invisible) – Dubukay Apr 21 '23 at 17:24
  • 1
    Add `panel.grid.minor.y = element_blank()` to your theme. – Seth Apr 21 '23 at 17:25
  • This is exact what I needed. Thank you so much! – Sharif Amlani Apr 21 '23 at 17:28
  • 2
    or `scale_y_continuous(minor_breaks = NULL)` – Jon Spring Apr 21 '23 at 17:28

0 Answers0