GGplot2-Aes问题填充

问题描述

我正在尝试为即将到来的足球比赛灯具创建一个图,其颜色基于表中球队的位置(Pos)。但是,如下图所示,填充似乎没有为各个图块选择正确的颜色。我已将以下数据包括在内。任何帮助将不胜感激!

    df %>%
ggplot() +
      geom_tile(aes(x=GW,y=team,fill=Pos),colour="black") +
      geom_text(aes(x=GW,label=oppo),size=3) +
      theme_void() +
      theme(axis.text = element_text(face = "bold")) +
      theme(axis.text.y = element_text(margin=margin(0,-20,0))) + 
      scale_x_continuous(position="top",breaks=1:15) +
      labs(caption=paste("xxx rocks | ",Sys.Date(),sep=""))

Plot

数据(dput(df)):

structure(list(team = c("CHE","EVE","LEE","NEW","LEI","SOU","ARS","WOL","MUN","AVL","CHE","CRY","MCI","SHU","TOT","WBA","BHA","BUR","WHU","FUL","LIV","BUR"),fdr = c(1070L,1070L,1350L,1150L,1100L,1030L,1220L,1260L,1060L,1190L,1080L,1270L,1250L,1200L,1090L,1180L,1050L,1310L,1170L,1020L),Pos = c(9,3,7,10,1,15,5,16,14,4,9,6,13,19,8,17,12,18,11,20,2,18),GW = c(4L,4L,5L,5L),home = c("CHE","WBA"),away = c("CRY",oppo = structure(c(6L,3L,12L,19L,18L,15L,8L,17L,11L,16L,20L,2L,1L,13L,7L,9L,14L,10L,6L,18L),.Label = c("ARS","WOL"),class = "factor"),G_A = c(6,5),G_F = c(6,2),PTS = c(4,0)),row.names = c(NA,-40L),class = "data.frame")

解决方法

您是否正在尝试根据对手的位置设置填充颜色?如果是这样,则需要在使用match进行绘制之前为每一行计算该值:

library(ggplot2)
library(dplyr)

df %>%
  mutate(oppo_pos = Pos[match(oppo,team)]) %>%
  ggplot() +
  geom_tile(aes(x = GW,y = team,fill = oppo_pos),colour = "black") +
  geom_text(aes(x = GW,label = oppo),size = 3) +
  theme_void() +
  theme(axis.text = element_text(face = "bold")) +
  theme(axis.text.y = element_text(margin=margin(0,-20,0))) + 
  scale_x_continuous(position = "top",breaks = 1:15) +
  labs(caption = paste("xxx rocks | ",Sys.Date(),sep = "")) +
  scale_fill_gradientn(colors = c("forestgreen","gold","tomato"))

https://code.kx.com/q/kb/pivoting-tables/