我试图在R中创建一个线图(时间与焦虑),x轴范围从上午10点到下午6点。但是,R按数字顺序重新排序值,图形看起来模糊不清。请参阅下面的矢量:
anxiety <- c(1, 1, 2, 2, 3.5, 4, 4.5, 5, 5)
time <- c(10, 11, 12, 1, 2, 3, 4, 5, 6)
plot(time, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimated)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)
我希望x轴值按时间顺序(上午10点,上午11点等)显示,并且图表反映了焦虑增加的近线性模式。
谢谢大家。
〜凯特琳
答案 0 :(得分:4)
如果您愿意尝试ggplot2
# data
anxiety <- c(1, 1, 2, 2, 3.5, 4, 4.5, 5, 5)
time <- c(10, 11, 12, 1, 2, 3, 4, 5, 6)
df <- data.frame(anxiety, time)
# order the level of time
df$time <- factor(df$time, order=TRUE, levels=time)
# plot
ggplot(df, aes(x=time, y=anxiety, group=1)) + geom_line()
答案 1 :(得分:1)
如果你的每个&#34; pm值为12,那么你得到你想要的东西:
time[4:9]<-12+time[4:9]
plot(time, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimatee)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)
注意:如果您想在xaxis中添加标签,可以使用以前的变量,以便更好地重命名时间:
time2<-c(time[1:3],time[4:9]+12)
plot(time2, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimatee)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)
axis(1,at=time2,labels=time)
答案 2 :(得分:1)
对于此任务和进一步分析,您可能会发现使用R的日期时间类来存储时间会更方便。这将需要预先做一些工作,但也会在稍后阐明您的数据集的含义。例如
time <- strptime(c("6:00 AM","7:00 AM","1:00 PM"),"%I:%M %p")
请注意,这将对日期(今天)和时区(用户的本地时区)进行一些推断。但是如果你也有这些信息,你可以在字符串中包含它,并修改format
参数。