gpt4 book ai didi

r - 在 ggplot2 中更改 x 轴刻度

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

我正在使用以下代码绘制我的数据框 d(在下面提供):

ggplot(data=d, aes(x=ID, y=Value)) + geom_line() 

enter image description here

我现在想更改 x 轴的轴刻度。为此,我使用:

ggplot(data=d, aes(x=d$ID, y=d$Value)) + 
geom_line() +
scale_x_discrete(breaks=1:8,
labels=c("05/11", "29/11", "11/12", "23/12",
"04/01", "16/01", "28/01", "09/02"))

然而,结果并不如预期。根本没有 x 轴刻度。 enter image description here

我的数据框d:

> str(d)
'data.frame': 10 obs. of 4 variables:
$ Value : num 0.021 0.0436 0.0768 0.0901 0.1128 ...
$ Statistic: Factor w/ 1 level "Variable": 1 1 1 1 1 1 1 1 1 1
$ ID : int 1 2 3 4 5 6 7 8 9 10
$ Variable : chr "Mean_Sigma0_VV" "Mean_Sigma0_VV" "Mean_Sigma0_VV" "Mean_Sigma0_VV" ...

> dput(d)
structure(list(Value = c(0.021008858735161, 0.0435905957091736,
0.0767780373205124, 0.0901182900951117, 0.11277978896612, 0.0990637045976107,
0.118897251291308, 0.10604101636234, 0.121525916187773, 0.104460360304768
), Statistic = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), class = "factor", .Label = "Variable"), ID = 1:10, Variable = c("Mean_Sigma0_VV",
"Mean_Sigma0_VV", "Mean_Sigma0_VV", "Mean_Sigma0_VV", "Mean_Sigma0_VV",
"Mean_Sigma0_VV", "Mean_Sigma0_VV", "Mean_Sigma0_VV", "Mean_Sigma0_VV",
"Mean_Sigma0_VV")), .Names = c("Value", "Statistic", "ID", "Variable"
), row.names = c(NA, -10L), class = "data.frame")

最佳答案

ID 是一个数字列,所以 ggplot2 使用连续刻度,而不是离散刻度:

ggplot(data=d, aes(x=ID, y=Value)) + 
geom_line() +
scale_x_continuous(breaks=1:8,
labels=c("05/11", "29/11", "11/12", "23/12",
"04/01", "16/01", "28/01", "09/02"))

enter image description here

或者,如果您想使用离散比例,则需要将 ID 转换为一个因子。但是,在这种情况下,ggplot2 通常不会将单独的 ID 值组合在一起并用一条线将它们连接起来。为此,您必须添加 group = 1(将所有内容放入同一组)。

d$ID <- factor(d$ID)

ggplot(data=d, aes(x = ID, y = Value, group = 1)) +
geom_line() +
scale_x_discrete(breaks=1:8,
labels=c("05/11", "29/11", "11/12", "23/12",
"04/01", "16/01", "28/01", "09/02"))

enter image description here

你可以看到这两个数字几乎但不完全相同。超出数据限制的轴范围扩展对于离散和连续尺度的工作方式略有不同。此外,连续尺度具有较小的网格线,而离散尺度则没有。

关于r - 在 ggplot2 中更改 x 轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794265/

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