【发布时间】:2018-05-27 09:59:19
【问题描述】:
我正在使用以下代码来绘制我的数据框d(如下提供):
ggplot(data=d, aes(x=ID, y=Value)) + geom_line()
我现在想更改 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"))
我的数据框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")
【问题讨论】:
-
“我现在想改变 x 轴的值” 是一个非常模糊的陈述。您可能想使用
scale_x_continuous,而不是scale_x_discrete。 -
我确实解决了这个问题,谢谢。我在另一个具有类似数据的代码中使用
scale_x_discrete,它正在工作。 -
只是想指出,每次您在
aes()语句中使用$运算符时,您的代码都可能损坏。即使它看起来有效,但它是错误的。 -
@ClausWilke,感谢您的指出。您的意思是使用
aes(x=ID, y=Value)比使用aes(x=d$ID, y=d$Value)更好。 “代码已损坏”是什么意思?这只是一个良好做法的问题吗? -
“代码错误”意味着行为未定义,仅仅因为它现在有效并不意味着它会一直有效。我建议您阅读美学映射。此外,如果在 SO 上没有关于此主题的任何内容(仔细搜索),您可以在此处专门提出一个单独的问题。