Reputation: 391
I'm trying to plot data in a barchart using lattice graphics. I'd like to sort the bars by one factor and group by another (i.e., position by the first factor and contrast within position by the second). However, I'd like to color the bars by the first (i.e., position) factor.
In the following example, the plot is rendered with paired red and blue bars. Instead, I'd like two adjacent red bars, two adjacent blue bars, and two adjacent green bars.
library(lattice)
data = runif( 6 )
facA = rep( c( "a", "b", "c" ), each = 2 )
facB = rep( c( "1", "2" ), 3 )
df = data.frame( "FactorA" = facA, "FactorB" = facB, "Data" = data )
df$FactorA = = as.factor( FactorA )
df$FactorB = = as.factor( FactorB )
test_colors = c( "red", "blue", "green" )
test_plot = barchart(FactorA ~ Data, groups = FactorB, data = df,
horizontal = TRUE, col = test_colors, origin = 0 )
plot( test_plot )
Thanks in advance!
Upvotes: 2
Views: 749
Reputation: 4216
If you wanted to do this with 'ggplot2', you would write it like so:
ggplot(df, aes(x=FactorA, y=data, group=FactorB, fill=FactorA)) +
geom_bar(stat="identity", position="dodge") +
coord_flip()
From there, it's just cosmetic tailoring to suit your tastes, including picking the colors for the fill.
Upvotes: 0
Reputation: 18759
This is not perfect but I think it does the trick (if I understood correctly your question).
barchart( FactorB ~ Data | FactorA, data = df, groups=FactorA,
horizontal = TRUE, col = test_colors, origin = 0, layout=c(1,3))
Factor B ~ Data | FactorA
means it divides your data in panels corresponding to FactorA
and inside each of these group, split according to FactorB
. The color follows what have been defined as the groups
.
Upvotes: 2