Evgeny
Evgeny

Reputation: 115

Barchart with reverse y-scale in lattice

I want a lattice barchart that looks like ggplot barchart with reverse y axis from here http://www.sthda.com/english/wiki/ggplot2-rotate-a-graph-reverse-and-flip-the-plot

In other words, I want to turn the barchart in lattice upside down, with the origin of bars at the top. I looked for the solution for quite some time thinking it should be easy, yet failed to find one...

require(lattice)
data <- data.frame(y = c(0.1, 0.4, 0.3, 0.23, 0.17, 0.27), x = c(1,2,3,4,5,6))
histogram <- barchart(data$y ~ data$x, horizontal = FALSE)
histogram

The code above produces regular barchart. What I want to do is to make bars start from the top, not from the bottom, with y scale reversed. In other words, I want this exact graph, but upside down.

Upvotes: 0

Views: 384

Answers (1)

DS_UNI
DS_UNI

Reputation: 2650

Here's one trick to do that:

plot the -y instead of y, and specify that the origin is 0, then you can change the labels on the y axis as you see fit

mydata <- data.frame(y = c(0.1, 0.4, 0.3, 0.23, 0.17, 0.27), x = c(1,2,3,4,5,6))

# fix where you want the ticks to be 
ticks_at <- seq(-0.5, 0, 0.1)
barchart(-y ~ x, 
         mydata, 
         horizontal = FALSE, 
         origin=0, 
         # set the position of the ticks and their labels 
         scales = list(y=list(at = ticks_at, 
                              labels = -1 * (ticks_at))),
         xlab = "x-Axis",
         ylab ="y-Axis")

You'll get something like this :

enter image description here

Upvotes: 0

Related Questions