Stephen Clark
Stephen Clark

Reputation: 596

ggplot2 rename the x-axis ticks changes the chart appearance

I have a plot (Plot #1 below) that is fine, but I would like to change the x-axis tick labels so that it says "Group 1", "Group 2", ... etc rather than "1", "2",... This I tried by specifying the new labels (Plot #2) or changing the grouping variable in x.df from a number to a character string/factor (Plots #3 and #4). However either the labels just disappear (Plot #2) or the plot changes strangely (Plots #3 and #4). Any advice?

library(ggplot2)

grp<-c(1,1,1,1,1,1,2,2,2,3,3,3,3,3,3,4,4,4,4,4)
rate<-c(6,7,8,9,6,7,8,9,6,7,8,9,6,7,8,9,6,7,8,9)

x.df<-data.frame(cbind(grp,rate))
x.df$rate<-as.factor(x.df$rate)

table(x.df$grp,x.df$rate)

# Plot #1 : Correct
ggplot(data = x.df, aes(x = grp, y = ..prop.., fill = rate))+ 
  geom_bar(stat = 'count', position = 'dodge')+ 
  xlab('Group')+ 
  ylab('%')

# Plot #2 : Correct but NO x-axis tick labels
ggplot(data = x.df, aes(x = grp, y = ..prop.., fill = rate))+ 
  geom_bar(stat = 'count', position = 'dodge')+ 
  xlab('Group')+ 
  ylab('%')+
  scale_x_discrete(breaks=1:4,
               labels=c("Group 1","Group 2","Group 3","Group 4"))

x.df$grp<-paste("Group",as.character(x.df$grp))

# Plot #3 : Incorrect graph but correct x-axis tick labels OK
ggplot(data = x.df, aes(x = grp, y = ..prop.., fill = rate))+ 
  geom_bar(stat = 'count', position = 'dodge')+ 
  xlab('Group')+ 
  ylab('%')

x.df$grp<-as.factor(x.df$grp)

#Plot #4 : as Plot #3
ggplot(data = x.df, aes(x = grp, y = ..prop.., fill = rate))+ 
  geom_bar(stat = 'count', position = 'dodge')+ 
  xlab('Group')+ 
  ylab('%')

Upvotes: 3

Views: 4113

Answers (1)

Anindya Mozumdar
Anindya Mozumdar

Reputation: 523

In plot 2, the easiest way is to use the limits argument and not breaks / labels.

ggplot(data = x.df, aes(x = grp, y = ..prop.., fill = rate))+ 
  geom_bar(stat = 'count', position = 'dodge')+ 
  xlab('Group')+ 
  ylab('%')+
  scale_x_discrete(limits=c("Group 1","Group 2","Group 3","Group 4"))

Upvotes: 1

Related Questions