簡體   English   中英

在R中更改x軸上的值的順序

[英]Changing the order of values on the x-axis in R

我試圖在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點等)呈現,並且圖表反映了焦慮增加的近線性模式。

謝謝大家。

〜凱特琳

如果你願意嘗試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()

在此輸入圖像描述

如果每個“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)

對於此任務和進一步分析,您可能會發現使用R的日期時間類來存儲時間會更方便。 這需要預先做一些工作,但也會在稍后闡明您的數據集的含義。 例如

time <- strptime(c("6:00 AM","7:00 AM","1:00 PM"),"%I:%M %p")

請注意,這將對日期(今天)和時區(用戶的本地時區)進行一些推斷。 但是,如果您還擁有該信息,則可以在字符串中包含該信息,並修改format參數。

然后,R將以非常清晰的方式繪制時間。 有關自定義x軸標簽的更多信息,請參閱此問題: 帶有x時間軸的R圖:如何強制刻度標簽為日期?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM