Home > database >  ggplot x axis label goes outside boundary and is partially cut off
ggplot x axis label goes outside boundary and is partially cut off

Time:10-29

My minimal example:

test_df <- data.frame(Year   = 1929:2021,
                      mydata = 1:93)

ggplot(test_df, aes(x = Year, y = mydata ))  
  geom_line()  
  labs(y = "S&P 500 EPS / Nominal GDP Normalized")  
  theme_bw()            
  theme(axis.title.x = element_text(size = 18, face = "bold"),
        axis.title.y = element_text(size = 18, face = "bold"),
        axis.text.x  = element_text(size = 14),
        axis.text.y  = element_text(size = 14)
  )

If you run it, you will see that the last x-axis label (2025) is only partially viewable -it gets cut off on the right. How can I make the plot area slightly smaller so that the last x-axis label is visible? If there is a legend on the right, this would be not be a problem, but given that I don't have a legend, it appears that a different solution is called for.

Sincerely and with many thanks in advance

Thomas Philips

CodePudding user response:

ggplot(test_df, aes(x = Year, y = mydata ))  
  theme(
        axis.text.x  = element_text(size = 14),
        plot.margin = margin(, 2, , , "cm")
  )

You can use the margin function in the theme system.

  • Related