繁体   English   中英

R ggplot2 geom_tile 几个图在同一个 plot

[英]R ggplot2 geom_tile Several graphs in the same plot

我正在研究以下网球数据:

library(ggplot2)
library(ggthemes)
library(grid)
library(gridExtra)
library(gtable)

Year<-c(1999:2020)
Player <- rep("Federer",22)
Rank<- c("Q1","3R","3R","4R","4R","W","SF","W","W","SF","F","W","SF","SF","SF","SF","3R",
     "SF","W","W","4R","SF")
Fre<-c("1R","4R","QF","1R","1R","3R","SF","F","F","F","W","QF","F","SF","QF","4R","QF",  
       "A","A","A","SF","NH")
Wim<-c("1R","1R","QF","1R","W","W","W","W","W","F","W","QF","QF","W","2R","F","F","SF",
       "W","QF","F","NH")
US<-c("Q2","3R","4R","4R","4R","W","W","W","W","W","F","SF","SF","QF","4R","SF","F",
       "A","QF","4R","QF","NH")

data <- data.frame(Year, Player, Rank, Fre, Wim,US)
data$Rank <- factor(data$Rank, levels = c("3R","4R","Q1","SF","F","W"))
data$Wim <- factor(data$Wim, levels = c("NH","1R","QF","SF","F","W"))
data$Fre <- factor(data$Fre, levels = c("NH","A","1R","3R","4R","Q1","QF","SF","F","W"))
data$US <- factor(data$US, levels = c("NH","A","3R","4R","Q1","Q2","QF","SF","F","W"))

我想像使用 Rank 一样可视化分类变量 Wim、Fre 和 US,但使用 geom_tile function 在同一个 plot 中。

仅具有 Rank 变量的 plot 如下所示:

在此处输入图像描述

我用于之前 plot 的命令是:

ggplot(data,aes(x=factor(Year),y=Player,fill=Rank)) + 
geom_tile(aes(fill=Rank),color="black", width=0.9,height=0.4) + 
scale_fill_manual(values=c("cornflowerblue","cyan2","aquamarine1","green",
"cyan4","yellow"))+
theme(axis.text.y  = element_text(color="black", size=8, face="bold"),
panel.background = element_rect(fill="white"))+
xlab("Years")+ylab("Tournament")+coord_flip()+  theme_bw()

What I want to do is to put three more diagrams in the same plot next to this with the rest three variables and the same colors for the levels plus some more colors for levels that don't appear in Rank variable.

我试图在我的代码中再添加三行,如下所示,但它不起作用。

ggplot(data,aes(x=factor(Year),y=Player,fill=Rank)) + 
geom_tile(aes(fill=Rank),color="black", width=0.9,height=0.4) + 
geom_tile(aes(fill=Fre),color="black", width=0.9,height=0.4) + 
geom_tile(aes(fill=Wim),color="black", width=0.9,height=0.4) + 
geom_tile(aes(fill=US),color="black", width=0.9,height=0.4) + 
scale_fill_manual(values=c("cornflowerblue","cyan2","aquamarine1", 
"green","cyan4","yellow"))+
theme(axis.text.y  = element_text(color="black", size=8, 
face="bold"),
panel.background = element_rect(fill="white"))+
xlab("Years")+ylab("Tournament")+coord_flip()+  theme_bw()

诀窍是将您的数据从其宽格式收集到更长的版本,而不是每个变量的列,您有一列指示引用了哪个变量,另一列指示该变量的值。 然后图形的语法会为您处理它。

library(tidyr)

data_long <-   gather(data, variable, value, -Year, -Player)

ggplot(data_long, aes(y = factor(Year), x = variable, fill = value)) + 
  geom_tile(color = "white", width = 0.9,height = 0.4)

当然,对于不同的级别,您将需要比目前更多的颜色。

我不知道您打算对更多玩家做什么,但是当您获得他们的值时,您可能想要使用 `+ facet_wrap(~Player) - 将所有内容保存在与此处相同类型的长数据框中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM