1
votes

I am plotting an interaction with this dataset:

X <- c(2.9, 4.0, 2.9, 4.0)
W <- c(2.5, 2.5, 4.3, 4.3)
Y <- c(1.8, 1.3, 1.5, 1.4)

df <- as.data.frame(cbind(X, W, Y)) 
df$wgroup <-
  case_when(W == 2.5 ~ "Low W",
            W == 4.3 ~ "High W")

df %>% 
  ggplot() + 
  aes(x = X, y = Y, group = wgroup) +
  geom_line(aes(linetype = wgroup)) + 
  geom_point() + 
  scale_linetype_manual(values=c("dashed", "solid"))

I would like to adjust the x axis ticks and labels so that there are two labels "Low X" and "High X" with just one tick in between them.

for example...enter image description here

I have tried both scale_x_continuous and scale_x_discrete, specifying labels and limits, but so far I haven't been able to get around the requirement that there be the same amount of labels and breaks.

1

1 Answers

3
votes

You could first change the labels to the factor levels, and then use grid to remove the tickmarks:

library(dplyr)
library(ggplot2)
library(grid)

rng <- c(min(df$X), mean(range(df$X)), max(df$X))
labs <- c("Low W", "", "High W")


pl <- df %>% 
  ggplot() + 
  aes(x = X, y = Y, group = wgroup) +
  geom_line(aes(linetype = wgroup)) + 
  geom_point() + 
  labs(x = "") +
  scale_linetype_manual(values=c("dashed", "solid")) +
  scale_x_continuous(breaks = rng, labels = labs,
                     expand = expand_scale(add = .3))

gg <- ggplotGrob(pl)

## when you look at gg$layout, you will see that the 7th element corresponds to the 
## bottom axis, furtehr investigation str(gg$grobs[[7]]) shows that the first
## child grob corresponds to the tick marks
## all to eb done is then to set the color of the first and the third tick mark to NA
gg$grobs[[7]]$children$axis$grobs[[1]]$gp$col <- c(NA, "grey20", NA)

grid.newpage()
grid.draw(gg)

Linechart