首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改变R中x轴上值的顺序

改变R中x轴上值的顺序
EN

Stack Overflow用户
提问于 2014-11-12 15:13:46
回答 3查看 4.3K关注 0票数 3

我试图在R中创建一个从上午10点到下午6点的x轴线图(时间和焦虑)。然而,R按数字顺序重新排序,图看起来模糊地‘。关于向量,请见下文:

代码语言:javascript
复制
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点等)。这张图反映了一种近乎线性的增长焦虑的模式。

谢谢大家。

~Caitlin

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-11-12 15:28:03

如果你愿意给ggplot2一次机会

代码语言:javascript
复制
# 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()

票数 4
EN

Stack Overflow用户

发布于 2014-11-12 15:20:37

如果您有12到每个"pm值“,您将得到您想要的:

代码语言:javascript
复制
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中添加标签,可以使用以前的变量,因此更好地重命名时间:

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2014-11-12 16:04:52

对于这个任务和进一步的分析,您可能会发现使用R的日期-时间类来存储时间更为方便。这将需要一些前期工作,但也澄清您的数据集的含义。例如

代码语言:javascript
复制
time <- strptime(c("6:00 AM","7:00 AM","1:00 PM"),"%I:%M %p")

请注意,这将对日期(今天)和时区(用户的本地时区)进行一些推断。但是,如果您也有该信息,则可以将其包含在字符串中,并修改format参数。

然后,r将以非常清晰的方式绘制时间图。有关自定义x轴标签的更多信息,请参见此问题:R plot with an x time axis: how to force the ticks labels to be the days?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26890238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档