Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a table using ggplot2

Tags:

r

ggplot2

I have a dataframe of football matches in la liga and I want to make a table where each row and column is a team name and each tile shows what the result was in the game between the two teams of row and column

I've tried many using geom_tile and ggplot2 in many different ways but the closest I've come to is the below code

library(dplyr)
library(engsoccerdata)
spain = as.data.frame(spain)
library(ggplot2)
game1 = filter(spain, Season == "2012")
ggplot(game1, aes(home, reorder(visitor,desc(visitor)), fill = FT)) + 
  geom_tile(color="white", size=1.5, stat="identity", height=1, width=1) + 
  scale_fill_brewer(palette = rep(c("blue","white"),30)) +
  geom_text(data=game1, aes(home, visitor, label = FT), size=rel(3)) +
  scale_x_discrete(position="top") + scale_y_discrete(expand = c(0, 0)) + 
  xlab("Home") + ylab("Visitor") +
  ggtitle("Laliga 2012")

I need the rows to be colored by oddity (odd rows white and even rows blue) Also I want the team names to be inside tiles over all I want my table to look like the first photo here but with striped lines

can anyone help me on modifications to my code?

like image 662
Alaleh Avatar asked Mar 06 '26 11:03

Alaleh


1 Answers

You can change the row-colors by specifying a new factor just for fill. Consider e.g. this

fillframe = as.numeric(reorder(game1$visitor,desc(game1$visitor)))
fillframe = as.factor(ifelse(fillframe %% 2 == 0, 1, 0))

ggplot(game1, aes(home, reorder(visitor,desc(visitor)), fill = fillframe)) + 
  geom_tile(color="white", size=1.5, stat="identity", height=1, width=1) + 
  scale_fill_manual(values = c("white", "lightblue")) +
  geom_text(data=game1, aes(home, visitor, label = FT), size=rel(3)) +
  scale_x_discrete(position="top") + scale_y_discrete(expand = c(0, 0)) + 
  xlab("Home") + ylab("Visitor") +
  ggtitle("Laliga 2012") +
  theme(legend.position = "None",
        axis.text.x = element_text(angle = 315))

enter image description here

For including the axis labels in the tiles, you'd have to expand the axis (since it is categorical, again by specifying additional factors), think this - but then you'd be better off just using Rmarkdown or HTML or so

like image 190
erocoar Avatar answered Mar 08 '26 01:03

erocoar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!