Skip to content

Instantly share code, notes, and snippets.

@chmullig
Last active August 29, 2015 13:57
Show Gist options
  • Save chmullig/9645567 to your computer and use it in GitHub Desktop.
Save chmullig/9645567 to your computer and use it in GitHub Desktop.
library(ggplot2)
require(grid)
require(gridExtra)
raw <- "name,assists,keypasses
\"Suárez, L\",10,68
Gerrard,9,51
Navas,6,49
Snodgrass,2,51
Rooney,10,49
Silva,8,66
Nasri,4,47
Mirallas,5,51
\"Henderson, J\",6,53
Hazard,7,83
Ozil,8,63
Sissoko,5,64"
df <- read.csv(textConnection(raw))
df <- df[order(df$assists) ,]
df <- transform(df, name=reorder(name, -assists) )
g1 <- ggplot(data = df, aes(x = reorder(name, assists), y = keypasses)) +
geom_bar(stat = "identity", fill="#377eb8") + ggtitle("Key Passes") +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.margin = unit(c(1,-1,1,0), "mm")) +
scale_y_reverse() + coord_flip()
g2 <- ggplot(data = df, aes(x = reorder(name, assists), y = assists)) +
geom_bar(stat = "identity", fill="#e41a1c") + ggtitle("Assists") +
theme(axis.title.x = element_blank(), axis.title.y = element_blank(),
axis.text.y = element_blank(), axis.ticks.y = element_blank(),
plot.margin = unit(c(1,0,1,-1), "mm")) +
scale_y_continuous(limits=c(0,80))+
coord_flip()
g.mid<-ggplot(df,aes(x=1,y=reorder(name, assists)))+geom_text(aes(label=reorder(name, assists)))+
ggtitle("")+
ylab(NULL)+
scale_x_continuous(expand=c(0,0),limits=c(0.94,1.065))+
theme(axis.title=element_blank(),
panel.grid=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.background=element_blank(),
axis.text.x=element_text(color=NA),
axis.ticks.x=element_line(color=NA),
plot.margin = unit(c(1,-1,1,-1), "mm"))
gg1 <- ggplot_gtable(ggplot_build(g1))
gg2 <- ggplot_gtable(ggplot_build(g2))
gg.mid <- ggplot_gtable(ggplot_build(g.mid))
png("2sided.png", width=650, height=480)
grid.arrange(gg1,gg.mid,gg2,ncol=3,widths=c(4/9,1/9,4/9))
dev.off()
#alternate stacked graph
ggplot(data = df, aes(x = reorder(name, -assists), y = keypasses)) +
geom_bar(stat = "identity", fill="#377eb8") +
geom_bar(aes(x = reorder(name, -assists), y = assists), stat="identity", fill="#e41a1c") +
ggtitle("Key Passes and Assists") +
ylab("Key Passes") +
xlab("Players (sorted by assists)") +
theme(axis.text.x=element_text(angle=45),
axis.title.y=element_text(color="#377eb8"))
ggsave("stacked.png", width=6.6, height=4.8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment