我有以下示例数据框,我想从 -4、-1 绘制:
test_x <- c(-3.5, -2, -1, -0.5)
test_y <- c(1,2,3,4)
df <- data.frame(x=test_x, y=test_y)
library(ggplot2)
ggplot(df, aes(x=x, y=y)) +
geom_point() +
xlim(-4, -1)
Run Code Online (Sandbox Code Playgroud)
我想显示 -4 刻度,我想排除 -0.5 点。但是,我也想更改 x 轴刻度标签。对于我发现的连续数据scale_x_continuous
ggplot(df, aes(x=x, y=y)) +
geom_point() +
scale_x_continuous(breaks=c(-4, -3, -2, -1), labels=c("a","b","c","d"))
Run Code Online (Sandbox Code Playgroud)
但是,这不显示a
刻度,也不排除 -0.5 处的点。尝试使用 x_lim 再次限制它会产生错误
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale
。
如何在仍然限制 x 轴范围的同时更改 x 轴刻度?
在规模内使用限制:
ggplot(df, aes(x = x, y = y)) +
geom_point() +
scale_x_continuous(breaks = c(-4, -3, -2, -1),
labels = c("a", "b", "c", "d"),
limits = c(-4, -1))
Run Code Online (Sandbox Code Playgroud)
请注意,通过应用限制,c(-4, -1)
我们会降低一分,因此我们会收到警告:
警告消息:删除了 1 行包含缺失值 (geom_point)。
作为 的替代方法limits
,您还可以使用coord_cartesian(xlim = c(-4, -1))
which 不会像设置限制那样更改基础数据(因此,您也不会收到有关已删除行的警告):
ggplot(df, aes(x=x, y=y)) +
geom_point() +
scale_x_continuous(breaks = c(-4, -3, -2, -1),
labels = c("a", "b", "c", "d")) +
coord_cartesian(xlim = c(-4, -1))
Run Code Online (Sandbox Code Playgroud)