简体   繁体   中英

R bar plot rename x axis ticks

I have a problem in renaming the x-axis ticks of my boxplot.

I have the following data.

CountWorkStudy          <- 14
CountLeisureSport       <- 26
CountSleepingRelax      <- 7
CountUnterwegs          <- 7

ActivityCountAll <- c(CountWorkStudy,CountLeisureSport,CountSleepingRelax,CountUnterwegs)
Names <- c(1,2,3,4)
#Names <- c("WorkStudy","LeisureSport","SleepingRelax","Unterwegs")
AllActivity <- cbind(ActivityCountAll,Names)
AllActivity <- as.data.frame(AllActivity)

Now I want to rename the x-axis ticks in the boxplot, however the result is a boxplot without any ticks.

ggplot(AllActivity, aes(x=Names, y=ActivityCountAll)) + 
  geom_bar(stat = "identity")+ scale_x_discrete(labels=c("1" = "Work", "2" = "SportLeisure","3" = "SleepRelax","4" = "Unterwegs"))

没有轴刻度的箱线图

Try this. The issue is that your x value is defined as numeric so the discrete scaling is not working. You can format it as factor in order to get the desired plot. Here the code:

#Code
ggplot(AllActivity, aes(x=factor(Names), y=ActivityCountAll)) + 
  geom_bar(stat = "identity")+
  scale_x_discrete(labels=c("1" = "Work", "2" = "SportLeisure","3" = "SleepRelax","4" = "Unterwegs"))

Output:

在此处输入图片说明

Or for further customization:

#Code2
ggplot(AllActivity, aes(x=factor(Names), y=ActivityCountAll)) + 
  geom_bar(stat = "identity")+
  scale_x_discrete(labels=c("1" = "Work", "2" = "SportLeisure","3" = "SleepRelax","4" = "Unterwegs"))+
  xlab('Names')

Output:

在此处输入图片说明

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