Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control number of minor grid lines in ggplot2?

Tags:

r

ggplot2

By default, it seems that ggplot2 uses a minor grid that is just half of the major grid. Is there any way to to break this up?

For example, I have a plot where the x-axis is years, and the major breaks are (1850, 1900, 1950, 2000). This means the minor grid points are at (1875, 1925, 1975), which is a little unintuitive for years. How can I make the minor grid appear at every decade?

like image 595
naught101 Avatar asked Oct 09 '12 05:10

naught101


People also ask

What is panel grid Major?

The panel. grid. major allows you to customize the major grid of the panel. library(ggplot2) ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point() + theme(panel.grid.major = element_line(color = "red", size = 0.5, linetype = 2)) Appending .

How do you add a minor gridline in R?

You need to use scale_x_continuous() and scale_y_continuous() with breaks and minor_breaks parameters. Parameter breaks will add major gridlines whereas minor_breaks will add minor gridlines.

What is Major Minor grid?

On value axes, major grid lines are drawn for every major axis division. Minor grid lines separate the units delineated by major grid lines. Minor grid lines, which can only appear on value axes, appear for every minor axis division. By default, major grid lines appear for value axes.

How do I get rid of grid lines in R?

To remove a particular panel grid, use element_blank() for the corresponding theme argument. For example to remove the major grid lines for the x axis, use this: p + theme(panel. grid.


1 Answers

You do it by explicitly specifying minor_breaks() in the scale_x_continuous. Note that since I did not specify panel.grid.major in my trivial example below, the two plots below don't have those (but you should add those in if you need them). To solve your issue, you should specify the years either as a sequence or just a vector of years as the argument for minor_breaks().

e.g.

 ggplot(movies, aes(x=rating)) + geom_histogram() +   theme(panel.grid.minor = element_line(colour="blue", size=0.5)) +   scale_x_continuous(minor_breaks = seq(1, 10, 1)) 

enter image description here

 ggplot(movies, aes(x=rating)) + geom_histogram() +   theme(panel.grid.minor = element_line(colour="blue", size=0.5)) +   scale_x_continuous(minor_breaks = seq(1, 10, 0.5)) 

enter image description here

like image 187
Maiasaura Avatar answered Sep 18 '22 10:09

Maiasaura