Home > OS >  can't display major grid lines in empty ggplot
can't display major grid lines in empty ggplot

Time:06-11

I need to create an empty plot with just axis, title, and grid breaks. I have come so far with this code:

library(ggplot2)
ggplot()   coord_cartesian(xlim=c(0, 100), ylim=c(0,100))  
  xlab("x axis")   ylab("y axis")  
  scale_y_continuous(breaks = seq(0,100,by=10), minor_breaks = seq(0, 100, by=5))  
  theme(axis.line.x = element_line(color="black", size = 1),
        axis.line.y = element_line(color="black", size = 1),
        panel.grid.major = element_line(colour="white", size=1),
        panel.grid.minor = element_line(colour="white", size=0.5))

It displays the minor grid lines, but for some reason the major lines can't display. Any clue on why and how I can see them? Thanks, enter image description here

CodePudding user response:

It is because the scale doesn't have any limits (which are normally computed from data) and major breaks can't be computed. The coords has limits, but the scale doesn't know about the coord limits. Might have to set the axis.ticks and axis.text theme elements to element_blank() too if you want it to be closer to your plot.

library(ggplot2)
ggplot()   coord_cartesian(xlim=c(0, 100), ylim=c(0,100))  
  xlab("x axis")   ylab("y axis")  
  scale_y_continuous(breaks = seq(0,100,by=10), minor_breaks = seq(0, 100, by=5),
                     limits = c(0, 100))  
  theme(axis.line.x = element_line(color="black", size = 1),
        axis.line.y = element_line(color="black", size = 1),
        panel.grid.major = element_line(colour="white", size=1),
        panel.grid.minor = element_line(colour="white", size=0.5))

Created on 2022-06-10 by the reprex package (v2.0.0)

  • Related