Reputation: 628
My question is similar to this question, in that I want the same result. However I don't think my data can be melted in the same way, as it's calculated from TRUE/FALSE values.
My data and graphs follow:
library(ggplot2)
library(gridExtra)
library(grid)
library(scales)
library(RColorBrewer)
#test dataframe
player <- c("a", "b", "a", "b", "c",
"a", "a", "b", "c", "b",
"c", "a", "c", "c", "a",
"c", "c", "c", "c", "c",
"c", "c", "c", "c", "c",
"c", "c", "c", "c", "c",
"b", "b", "b", "b")
is.winner <- c(TRUE, TRUE, TRUE, TRUE, TRUE,
FALSE, TRUE, TRUE, TRUE, FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE,
TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, FALSE, FALSE)
df <- data.frame(player, is.winner)
df$is.winner <- factor(df$is.winner, levels=c("TRUE", "FALSE")) #swap T/F bars
# Stacked wins and losses
aa <- ggplot(data=df, aes(x=player, fill=is.winner)) +
stat_bin(geom = "bar", position = "stack") +
scale_fill_brewer(palette="Set2") +
coord_flip()
# Win percentage
ab <- ggplot(data=df, aes(x=player)) +
geom_bar(aes(fill=is.winner),position='fill')+
scale_y_continuous(labels=percent)+
scale_fill_brewer(palette="Set2") +
xlab("player") +
ylab("win%") +
coord_flip()
grid.arrange(aa,ab,ncol=2)
The goal is to easily be able to look at a players win count and win percentage, shown on different graphs above. I think the facet-style graph would be great, though I'm not sure if the way I've handled my data affects my ability to make use of that. Thanks for any insight.
Upvotes: 1
Views: 87
Reputation: 77096
you could make a dummy facetting variable,
d <- lattice::make.groups(first=df, second=df)
ggplot(data=d, aes(x=player, fill=is.winner)) +
facet_grid(which~., scales="free") +
geom_bar(position = "stack", data=subset(d, which=="first")) +
geom_bar(position = 'fill', data=subset(d, which=="second")) +
scale_fill_brewer(palette="Set2")
interestingly, flipping the coordinates produces an incorrect plot, at least with the dev version of ggplot2.
last_plot() + coord_flip()
Upvotes: 1