# [R] Can this be done in ggplot?

Axel Urbiz axel.urbiz at gmail.com
Sat Apr 15 17:25:02 CEST 2017

```Thanks Kenneth. That is the right idea for what I’m after. However,
creating a combined factor based on “g” and “f” is creating unwanted spaces
between the bars in the plot (I’d like to keep them adjacent within levels
of “g” as shown in my first plot).

I had the idea that ordering bars in ggplot with respect to a variable
within factor levels would be easier, but looks it is not.

Thanks again,
Axe.

On Apr 14, 2017, at 10:40 PM, Kenneth Roy Cabrera Torres <
krcabrer at une.net.co> wrote:

A very dirty solution.

I hope someone can give a better solution:

library(ggplot2)
set.seed(1)
df <- expand.grid(g = factor(1:4), f = factor(c("a", "b", "c")))
df <- df[-1, ] # some factors are not present in certain groups
df\$v <- runif(nrow(df))

library(dplyr)

df <- df %>% arrange(g, desc(v))
df\$nv <- with(df, factor(paste(g,f)))
df\$nv <- factor(df\$nv, levels = df\$nv)

ggplot(df, aes(x = nv , y = v, fill = f)) +
geom_bar(position="dodge", stat = "identity")

El 14/04/17 a las 10:08, Axel Urbiz escribi�:

Hi,

I need to bars to display in order based on the values of "v" within each
group "g". Is this possible?

library(ggplot2)
set.seed(1)
df <- expand.grid(g = 1:4, f = factor(c("a", "b", "c")))
df <- df[-1, ] # some factors are not present in certain groups
df\$v <- runif(nrow(df))

ggplot(df, aes(x = g, y = v, fill = f)) +
geom_bar(position="dodge", stat = "identity")

Thanks,
Axel.

[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
and provide commented, minimal, self-contained, reproducible code.

[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help