Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot geom_bar - 'rotate and flip'?

Tags:

r

ggplot2

test <- data.frame(
    y=seq(18,41,1),
    x=24:1
)

ggplot(test, aes(y=y, x=x)) + geom_bar(stat="identity", aes(width=1)) + 
    opts( axis.text.x = theme_blank(), axis.ticks.x = theme_blank()) + 
    scale_x_continuous(breaks=NULL) + 
    coord_cartesian(ylim = c(17, 42))

enter image description here

As far as the rotating and flipping is concerned, I'd like what is the y axis in this plot to be along the top, and what is the x axis to be down the right hand side. So the bars are coming 'out' of the right hand side of the plot, with the longest/tallest at the top, shortest at the bottom. If it's rotated clockwise 90 degrees, and then flipped over a vertical line that would achieve it.

coord_flip() and scale_y_reverse() get someway down the right path.

Edit:

I guess this is pretty close, just need to get that y axis to the top of the graph.

ggplot(test, aes(y=y, x=x)) + geom_bar(stat="identity", aes(width=1)) + 
    opts(axis.text.y = theme_blank(), axis.ticks.y = theme_blank()) + 
    scale_x_continuous(breaks=NULL) + scale_y_reverse() + coord_flip()  + scale_x_reverse()
like image 716
nzcoops Avatar asked Jul 13 '12 07:07

nzcoops


People also ask

What is the difference between using Geom_bar () and Geom_bar Stat identity )?

By default, geom_bar uses stat="bin". This makes the height of each bar equal to the number of cases in each group, and it is incompatible with mapping values to the y aesthetic. If you want the heights of the bars to represent values in the data, use stat="identity" and map a value to the y aesthetic."

What does Geom_bar do in R?

geom_bar() specifies that we want to plot a bar chart. Notice that we did not map any variables to the y-axis. Because of this, by default, ggplot simply counted up the number of records by category (i.e., by gender). So the length of the bar (the y-axis, in this case) represents the count of the number of records.

How do I flip the Y axis in R?

It is a common need in dataviz to flip the Y axis upside down. In base R this is pretty easy to do: you just have to reverse the values of the ylim argument.


1 Answers

Not exactly what you describe, but perhaps close enough?

ggplot(test, aes(y=y, x=x)) + geom_bar(stat="identity", aes(width=1)) +
  coord_flip() +
  xlim(24, 1) +
  ylim(42, 0)

The trick is to have the xlim and ylim arguments in reverse order. Your axis positions are still bottom and left...

enter image description here

like image 89
Andrie Avatar answered Sep 20 '22 22:09

Andrie