gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:26:26 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com