我正在绘制与此数据集的交互:
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"))
我想调整x轴刻度和标签,以便有两个标签“ Low X”和“ High X”,并且它们之间只有一个刻度。
我已经尝试scale_x_continuous
和scale_x_discrete
来指定标签和限制,但是到目前为止,我还无法解决标签和中断数量相同的要求。
答案 0 :(得分:3)
您可以先将标签更改为因子水平,然后使用grid
删除刻度线:
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)