An old code that used to work perfectly no longer works with 0.9.3. The issue is related to the use of facets, free scales and coord flip.
Here is a way to reproduce:
data set: d.csv:
"Priority","Owner","Project"
"Medium","owner7","Team4"
"Medium","owner1","Team1"
"Low","","Team3"
"High","owner6","Team3"
"Medium","","Team4"
"Medium","owner3","Team1"
"Medium","owner2","Team1"
"Medium","owner5","Team2"
"Low","owner4","Team2"
"Critical","","Team2"
"Medium","owner2","Team1"
"High","","Team4"
Code:
data <- read.csv(file="d.csv",head=TRUE)
attach(data)
p3 <- ggplot(data,aes(x=Owner,fill=Priority))+
geom_bar(aes(y=..count..)) +
facet_wrap(~ Project, nrow=2, scales="free") +
opts(legend.position="none")
This creates a faceted plot but I need the axes flipped. Previously, adding a coord_flip() did the trick but now the new ggplot does not permit using free scales and coord_flip together. Is there any other way to turn the facet axes around? The free scales are important to me. Thanks for any pointers.
This is the second or third time I have run into this problem myself. I have found that I can hack my own solution by defining a custom geom.
geom_bar_horz <- function (mapping = NULL, data = NULL, stat = "bin", position = "stack", ...) {
GeomBar_horz$new(mapping = mapping, data = data, stat = stat, position = position, ...)
}
GeomBar_horz <- proto(ggplot2:::Geom, {
objname <- "bar_horz"
default_stat <- function(.) StatBin
default_pos <- function(.) PositionStack
default_aes <- function(.) aes(colour=NA, fill="grey20", size=0.5, linetype=1, weight = 1, alpha = NA)
required_aes <- c("y")
reparameterise <- function(., df, params) {
df$width <- df$width %||%
params$width %||% (resolution(df$x, FALSE) * 0.9)
OUT <- transform(df,
xmin = pmin(x, 0), xmax = pmax(x, 0),
ymin = y - .45, ymax = y + .45, width = NULL
)
return(OUT)
}
draw_groups <- function(., data, scales, coordinates, ...) {
GeomRect$draw_groups(data, scales, coordinates, ...)
}
guide_geom <- function(.) "polygon"
})
This is just copying the geom_bar code from the ggplot2 github and then switching the x and y references to make a horizontal barplot in the standard Cartesian coordinators.
Note that you must use position='identity'
and possibly also stat='identity'
for this to work. If you need to use a position other than identity then you will have to eddit the collide function for it to work properly.
Update per late 2016: This bug with coord_flip
, facet_grid
and scales="free"
has been fixed in the development version of ggplot2
. You can install it with
install.packages("devtools")
devtools::install_github("hadley/ggplot2")
Note, try both free_x
and free_y
depending on your needs, because it is not always clear what x
and y
mean when you have flipped the coordinates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With