In R STUDIO, how to reverse the order of x-axis (numeric), and also change the direction of graph?

In R STUDIO, how to reverse the order of x-axis (numeric), and also change the direction of graph?

Here is one data

cv<- rep(c("cv1","cv2"), each=5)
value<- c(50,40,30,20,10,45,38,26,22,17)
index<- rep(c(5,15,27,36,45), each=2)
dataA<- data.frame(cv, value, index)
data

Then I make a regression graph.

library (ggplot2)

ggplot(data=dataA, aes(x=index, y=value))+
  geom_smooth(aes(fill=cv), method=lm, level=0.95, se=FALSE, linetype=1, 
  size=0.5, color="Black", formula=y~x) +
  geom_point (aes(shape=cv, fill=cv), col="Black", size=3) +
  scale_x_continuous(breaks = seq(-0, 60, 10), limits = c(-0, 60)) + 
  scale_y_continuous(breaks = seq(0,70,10), limits = c(0,70)) +
  labs(x="Environmental Index", y="Kernel number") +
  theme_grey(base_size=15, base_family="serif")+
  theme(legend.position= 'none',
  axis.line= element_line(size=0.5, colour="black")) +
  windows(width=5.5, height=5)

Now, I’d like to reverse the order of x-axis by descending (60 to 0). So I delete the code, scale_x_continuous(breaks = seq(-0, 60, 10), limits = c(-0, 60)) and add a new code, scale_x_reverse(limits = c(60,0))

So the whole code is below.

ggplot(data=dataA, aes(x=index, y=value))+
  geom_smooth(aes(fill=cv), method=lm, level=0.95, se=FALSE, linetype=1, 
              size=0.5, color="Black", formula=y~x) +
  geom_point (aes(shape=cv, fill=cv), col="Black", size=3) +
  scale_x_reverse(limits = c(60,0)) +
  scale_y_continuous(breaks = seq(0,70,10), limits = c(0,70)) +
  labs(x="Environmental Index", y="Kernel number") +
  theme_grey(base_size=15, base_family="serif")+
  theme(legend.position= 'none',
        axis.line= element_line(size=0.5, colour="black")) +
  windows(width=5.5, height=5)

Now, you can see the order of x-axis is changed and also the direction of the graph is changed.

How to adjust unit of the axis?

To adjust unit of x-axis, put breaks= seq(60, 0, by= -10) inside scale_x_reverse(). Remember!! the unit should be a negative value (i.e. -10).

The whole code is below

ggplot(data=dataA, aes(x=index, y=value))+
  geom_smooth(aes(fill=cv), method=lm, level=0.95, se=FALSE, linetype=1, 
              size=0.5, color="Black", formula=y~x) +
  geom_point (aes(shape=cv, fill=cv), col="Black", size=3) +
  scale_x_reverse(limits = c(60,0), breaks= seq(60, 0, by = -10)) +
  scale_y_continuous(breaks = seq(0,70,10), limits = c(0,70)) +
  labs(x="Environmental Index", y="Kernel number") +
  theme_grey(base_size=15, base_family="serif")+
  theme(legend.position= 'none',
        axis.line= element_line(size=0.5, colour="black")) +
  windows(width=5.5, height=5)

Leave a Reply

If you include a website address in the comment section, I cannot see your comment as it will be automatically deleted and will not be posted. Please refrain from including website addresses.