BhishanPoudel
BhishanPoudel

Reputation: 17144

How to plot x axis on top and y axis inverted in R Programming?

In general when we do plotting, the plot has the x-axis on bottom (left to right) and y-axis on left (bottom to top).
For example, In R-programming I have a code like this:

t <- seq(0,1,0.2)       # need t values in top x axis
plot(t,t^2,type="l")    # need t^2 values in inverted y-axis

Now, if we want plot so that the x-axis is on top (left to right) and y-axis inverted (top to bottom).
How can we achieve such a feat in R-programming? I searched following links in stackoverflow but they could not meet my requirements:
How to invert the y-axis on a plot

Invert y-axis in barplot

Upvotes: 2

Views: 8503

Answers (1)

rawr
rawr

Reputation: 20811

Check out ?axis

t <- seq(0,1,0.2)
plot(t,t,type="l", xaxt = 'n', yaxt = 'n')
lines(t,t^2,col="green")
lines(t,t^3,col="blue")
axis(3)
axis(2, at = pretty(t), labels = rev(pretty(t)))

enter image description here

I'm not sure why the .0 gets dropped on the y, but you can use labels = format(rev(pretty(t)), digits = 1) for consistency

EDIT

to reverse the entire plot about one of the axes, just reverse the xlim or ylim of the plot, and you don't need to worry about flipping or negating your data:

t <- seq(0,1,0.2)
plot(t,t,type="l", xaxt = 'n', yaxt = 'n', ylim = rev(range(t)))
lines(t,t^2,col="green")
lines(t,t^3,col="blue")
axis(3)
axis(2, at = pretty(t), labels = format(pretty(t), digits = 1), las = 1)

enter image description here

Upvotes: 8

Related Questions