I have below ggplot
library(ggplot2)
ggplot (structure(list(Group1 = c('A','B', 'B','A', 'B','B', 'A', 'B', 'B'), Val = c(40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59)), row.names = c(NA, -9L), class = "data.frame"), aes (x = Group1, y = Val)) +
geom_line () +
scale_y_continuous (breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54) ,
sec.axis = sec_axis(~.,
breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54)))
Above codes generates below plot
As you can see, there are multiple horizontal grid-lines near points like 20.31 and 0 etc.
Could you please help to understand where they are coming from and how to get rid of them?
The issue has nothing to do with the secondary axis. The additional grid lines are the minor grid lines which are visible due to your irregular (major) breaks. You can drop them using e.g. minor_breaks=NULL
:
library(ggplot2)
ggplot(structure(list(Group1 = c("A", "B", "B", "A", "B", "B", "A", "B", "B"), Val = c(
40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59
)), row.names = c(NA, -9L), class = "data.frame"), aes(x = Group1, y = Val)) +
geom_line() +
scale_y_continuous(
breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54),
sec.axis = sec_axis(~.,
breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54)
),
minor_breaks = NULL
)
EDIT And if you want minor breaks at the midpoints of the breaks you could do:
library(ggplot2)
breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54)
minor_breaks <- sort(breaks)[-1] - diff(sort(breaks)) / 2
ggplot(structure(list(Group1 = c("A", "B", "B", "A", "B", "B", "A", "B", "B"), Val = c(
40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59
)), row.names = c(NA, -9L), class = "data.frame"), aes(x = Group1, y = Val)) +
geom_line() +
scale_y_continuous(
breaks = breaks,
minor_breaks = minor_breaks,
sec.axis = sec_axis(~.,
breaks = breaks
)
)