r - ggplot2 Grouping histogram bars -


i have problems grouping bars of histogram.

this part of dataset:

data <- structure(list(color = structure(c(1l, 2l, 1l, 2l, 1l, 2l, 1l, 2l), .label = c("blue", "red"), class = "factor"),                        group = structure(c(1l, 1l, 2l, 2l, 3l, 3l, 3l, 3l), .label = c("group1", "group2", "group3"), class = "factor"),                        id = structure(1:8, .label = c("a1", "a2", "b1", "b2", "c1", "c2", "d1", "d2"), class = "factor"),                         value = c(194l, 1446l, 0l, 17l, 77l, 2565l, 223l, 61l)),                    .names = c("color", "group", "id", "value"), class = "data.frame", row.names = c(na, -8l)) 

i build histogram follow:

ggplot(data, aes(id, value)) + geom_bar(aes(fill = color), position = "dodge", stat="identity") + scale_fill_manual(values=c("blue", "red")) 

now group bars of histogram variable group, found impossible using facet_wrap:

ggplot(data, aes(id, value)) + geom_bar(aes(fill = color), position = "dodge", stat="identity") + scale_fill_manual(values=c("blue", "red")) + facet_wrap(. ~ group) 

error in layout_base(data, vars, drop = drop) : @ least 1 layer must contain variables used facetting.

it fine having groups spaced each other.

how can that? can me?

you need remove .:

ggplot(data, aes(id, value)) +    geom_bar(aes(fill = color), position = "dodge", stat="identity") +    scale_fill_manual(values=c("blue", "red")) +    facet_wrap( ~ group) 

this give following plot:

enter image description here

when want improve plot, include scales = "free_x" in facet_wrap part. rid off unnecessary values on x-axis:

ggplot(data, aes(id, value)) +    geom_bar(aes(fill = color), position = "dodge", stat="identity") +    scale_fill_manual(values=c("blue", "red")) +    facet_wrap( ~ group, scales = "free_x") 

this give you:

enter image description here

if want bars of equal width, it's better use space argument in facet_grid:

ggplot(data, aes(id, value)) +    geom_bar(aes(fill = color), position = "dodge", stat="identity") +    scale_fill_manual(values=c("blue", "red")) +    facet_grid(. ~ group, scales = "free_x", space = "free_x") 

this gives:

enter image description here


Comments

Popular posts from this blog

apache - setting document root in antoher partition on ubuntu -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -

Process 'command 'F:\android-sdk\build-tools\21.1.2\aapt.exe'' finished with non-zero exit value 1 -