Let's say I have a plot generated by this code:
library(ggplot2); ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()
I would like to remove an arbitrary horizontal (or vertical) gridline, perhaps v = 12500 or v = 15000 (or both). I addition, I would like to keep the respective tickmark(s). Is there any relatively easy way to do this?
For the clarity, I do not want to get rid of all minor gridlines, especially not all the gridlines.
In this article, we will discuss how to remove axis labels and ticks in ggplot2 in R Programming Language. The axes labels and ticks can be removed in ggplot using the theme () method. This method is basically used to modify the non-data components of the made plot. It gives the plot a good graphical customized look.
How to Remove Gridlines in ggplot2 (With Examples) The easiest way to remove gridlines in ggplot2 is to use theme_classic() : ggplot(df, aes (x=x, y=y)) + geom_point() + theme_classic()
The R code below set the position of tick marks on the y axis of the box plot. The function scale_y_continuous () and the argument breaks are used to choose where the tick marks appear : Tick mark labels can be formatted to be viewed as percents, dollars or scientific notation.
The theme () method is used to work with the labels, ticks, and text of the plot made. The labels and ticks are aligned to the element_blank () method in order to remove them. theme (axis.text.x = , axis.ticks.x = , axis.text.y = , axis.ticks.y = )
You can try something like this, without having to use grid to modify the underlying object.
First we get the coordinates of major/minor
ymajor = ggplot_build(p)$layout$panel_params[[1]]$y.major_source
yminor = ggplot_build(p)$layout$panel_params[[1]]$y.minor_source
yminor = setdiff(yminor,ymajor)
ymajor_cols = ifelse(ymajor == 15000,"transparent","white")
yminor_cols = ifelse(yminor == 12500,"transparent","white")
Then we add to your plot by specifying
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()+
theme(panel.grid.major.y = element_line(colour = ymajor_cols),
panel.grid.minor.y = element_line(colour = yminor_cols))
I would actually prefer specifying the major and minor breaks and specifying them in the plot, the below code gives the same results:
ymajor = c(0,5000,10000,15000)
yminor = c(0,2500,12500,17500)
ymajor_cols = ifelse(ymajor == 15000,"transparent","white")
yminor_cols = ifelse(yminor == 12500,"transparent","white")
ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point()+
scale_y_continuous(breaks=ymajor,minor_breaks = yminor)+
theme(panel.grid.major.y = element_line(colour = ymajor_cols),
panel.grid.minor.y = element_line(colour = yminor_cols))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With