如何使用 ggplot2 绘制具有选定行数的变量?
How to plot a variable with selected number of rows using ggplot2?
我的数据帧(速度)示例如下,有 45122 个观测值。
A B C
1 0.06483121 0.08834364 0.05814113
2 0.06904103 0.13169238 0.06082291
3 0.05556961 0.09767185 0.06039383
4 0.06483121 0.13388726 0.05996474
5 0.06651514 0.11632827 0.04891578
6 0.06904103 0.11687699 0.05953565
...
......
45122 0.06212749 0.08307191 0.07422524
我可以使用下面的代码选择我喜欢的观察次数来创建一个简单的图:
(时间循环模式 - y 轴显示速度,x 轴显示 0 到 500)
plot(speed[1:500,3], type="l", ylab="speed", xlab="unit time")
我正在尝试对 ggplot2 做同样的事情,但它给了我一个直方图。
如何使用 ggplot 绘制类似的图?
我们 subset
前 500 行和第三个变量 ('C') 使用 [
。请注意,我们必须添加 drop=FALSE
,因为默认值为 drop=TRUE
。根据 ?"["
,如果 drop=TRUE
,结果将被强制到可能的最低维度,即在这种情况下 vector
.
speed1 <- speed[1:500,3, drop=FALSE]
我们在 aes
中指定 'x' (1:nrow(speed1)
) 和 'y' 变量,将 geom_line()
用于 line
图和xlab
和 ylab
指定 'x axis' 和 'y axis' 的标签。
library(ggplot2)
ggplot(speed1, aes(x=1:nrow(speed1), y=C))+
geom_line() +
ylab('speed') +
xlab('unit time')
数据
set.seed(24)
speed <- as.data.frame(matrix(abs(rnorm(45122*3)), ncol=3,
dimnames=list(NULL, LETTERS[1:3])))
我的数据帧(速度)示例如下,有 45122 个观测值。
A B C
1 0.06483121 0.08834364 0.05814113
2 0.06904103 0.13169238 0.06082291
3 0.05556961 0.09767185 0.06039383
4 0.06483121 0.13388726 0.05996474
5 0.06651514 0.11632827 0.04891578
6 0.06904103 0.11687699 0.05953565
...
......
45122 0.06212749 0.08307191 0.07422524
我可以使用下面的代码选择我喜欢的观察次数来创建一个简单的图:
(时间循环模式 - y 轴显示速度,x 轴显示 0 到 500)
plot(speed[1:500,3], type="l", ylab="speed", xlab="unit time")
我正在尝试对 ggplot2 做同样的事情,但它给了我一个直方图。
如何使用 ggplot 绘制类似的图?
我们 subset
前 500 行和第三个变量 ('C') 使用 [
。请注意,我们必须添加 drop=FALSE
,因为默认值为 drop=TRUE
。根据 ?"["
,如果 drop=TRUE
,结果将被强制到可能的最低维度,即在这种情况下 vector
.
speed1 <- speed[1:500,3, drop=FALSE]
我们在 aes
中指定 'x' (1:nrow(speed1)
) 和 'y' 变量,将 geom_line()
用于 line
图和xlab
和 ylab
指定 'x axis' 和 'y axis' 的标签。
library(ggplot2)
ggplot(speed1, aes(x=1:nrow(speed1), y=C))+
geom_line() +
ylab('speed') +
xlab('unit time')
数据
set.seed(24)
speed <- as.data.frame(matrix(abs(rnorm(45122*3)), ncol=3,
dimnames=list(NULL, LETTERS[1:3])))