r - 如何在仍然限制 x 轴范围的同时更改 x 轴刻度?

标签 r ggplot2

我有以下示例数据框,我想从 -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)

enter image description here

我想显示 -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"))

enter image description here

但是,这不显示 a 刻度,也不排除 -0.5 处的点。尝试用 x_lim 再次限制它会给出错误 “x”的比例已经存在。为“x”添加另一个比例,它将替换现有的比例

如何在限制 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))

注意,通过应用限制c(-4, -1),我们会丢掉一分,所以我们会收到警告:

Warning message: Removed 1 rows containing missing values (geom_point).


作为 limits 的替代方案,您还可以使用 coord_cartesian(xlim = c(-4, -1)),它不会像设置限制那样更改基础数据会(因此,您也不会收到有关已删除行的警告):

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))

关于r - 如何在仍然限制 x 轴范围的同时更改 x 轴刻度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369884/

相关文章:

r - 用roxygen2记录数据集

r - 使用 ggplot 绘制 y = mx + c

r - 如何在我的一个方面标签中使用希腊符号?

r - 如何在时间序列中途更改 ggplot2 中的线条属性?

r - 如何检查值是否为数字?

r - 有没有什么方法可以使用 Shiny 的操作按钮递归地将行添加到 data.frame 中?

r - ggplot 中 geom_point (scale_colour_manual) 的填充和边框颜色

r - R中不同组的时间序列多重图

r - 在 Windows 上安装 Rmpi​​ 包时出错

r - 使用 dplyr 根据其他列的值更改列的内容