简体   繁体   English

使用ggplot2重命名意大利面条图中x轴上的刻度线

[英]Rename tick marks on x-axis in spaghetti plot using ggplot2

I am quite new to R and I am trying to create a spaghetti plot to compare in 4 groups the percentage of patients taking rescue medication, at different timepoints (1 hour after surgery, 4 hours, 8 hours and post-operative day 1 morning and post-operative day 1 afternoon). 我对R很陌生,我试图创建一个意大利面条图,以比较4组在不同时间点(手术后1小时,手术后4小时,8小时和术后1天早上和之后,术后第1天下午)。

After playing around, I created a decent graph, starting from this code: 玩了之后,我从以下代码开始创建了一个不错的图形:

plot <-- ggplot(data=rescue, aes(Measurement, Percentage, color=factor(Group))) + geom_line()

With several commands, I adjusted the graph to my liking and I have this: 通过几个命令,我根据自己的喜好调整了图形,并得到了以下结果: 在此处输入图片说明

I would like to replace 1, 2, 3, 4, 5 on the x-axis with the labels 1 hour , 4 hours , 8 hours , POD1 Morning and POD1 Afternoon . 我想用标签1 hour4 hours8 hoursPOD1 MorningPOD1 Afternoon替换x-axis1 hour

I searched this site and google and came up with this code: 我搜索了该网站和google,并想到了以下代码:

plot1 <-- plot + scale_x_discrete(labels=c("1"="1 hour", "2"="4 hours", "3"="8 hours", "4"="POD1 Morning", "5"="POD1 Afternoon"))

I also tried levels=c(1,2,3,4,5) and labels=c("1 hour", "4 hours", etc) but all I get is an empty x-axis , no new labels. 我也尝试了levels=c(1,2,3,4,5)labels=c("1 hour", "4 hours", etc)但是我得到的只是一个空的x-axis ,没有新的标签。 I cannot seem to make it work. 我似乎无法使其工作。 In another post I read the advice to use xaxt="n" , but I cannot get that to work with ggplot2 . 在另一篇文章中,我阅读了使用xaxt="n"的建议,但无法将其与ggplot2一起ggplot2

Could anyone please help me? 谁能帮我吗? Thank you so much! 非常感谢!

Consider using breaks in scale_x_discrete() 考虑在scale_x_discrete()使用中断

plot <- ggplot(data=rescue, aes(Measurement, Percentage, color=factor(Group))) + 
        geom_line() +  
        scale_x_discrete(breaks=c(1, 2, 3, 4, 5), 
                labels=c("1 hour", "4 hours", "8 Hours", "POD1 Morning", "POD1 Afternoon"))

You're trying to apply a discrete axis to a continues variable (Measurement). 您正在尝试将离散轴应用于连续变量(测量)。 The fix would be to turn Measurement into factors: 解决方法是将Measurement变成因素:

plot <-- ggplot(data=rescue, aes(factor(Measurement), Percentage, color=factor(Group))) + geom_line()

And you'll probably want to manually change the label by adding on 您可能需要通过添加手动更改标签

+ labs(x = 'Measurement')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM