简体   繁体   中英

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).

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 .

I searched this site and google and came up with this code:

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. 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 .

Could anyone please help me? Thank you so much!

Consider using breaks in 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:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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