如何在水平条形图中绘制单个组件?

时间:2017-02-21 23:16:35

标签: r ggplot2

我正在尝试分析足球数据,其中特定传球和目标在3个赛段或比赛期间被跟踪。还跟踪一个团队所采用的防御结构或模式的类型。我的数据集的一个例子如下:

# Example data
Time <- c(1, 1, 2, 3, 4, 5, 6, 9, 1, 2, 3, 5, 5, 7, 9, 1, 2, 4, 7, 9)
Event <- c("Pass", "Pass", "Pass", "Goal", "Pass", "Pass", "Goal", "Pass", "Pass", 
           "Pass", "Pass", "Pass", "Pass", "Pass", "Pass", "Goal", "Pass", "Pass", "Pass", "Goal")
Term <- c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3) 
Symbol <- c("P", "P", "P", "G", "P", "P", "G", "P", "P", 
            "P", "P", "P", "P", "P", "P", "G", "P", "P", "P", "G")
By <- c("Home", "Away", "Home", "Home", "Home", "Away", "Away", "Away", "Home", 
            "Home", "Home", "Away", "Away", "Away", "Home", "Home", "Home", "Away", "Away", "Away")
Mode <- c("Press", "Press", "Press", "Forward", "Forward", "Forward", "Forward", "Press", "Press", 
            "Press", "Press", "Press", "Press", "Forward", "Forward", "Forward", "Forward", "Press", "Press", "Forward")
# Make data.frame
GameData <- data.frame(Time, Event, Term, Symbol, By, Mode)
# Make factors
GameData$Event <- as.factor(GameData$Event)
GameData$Symbol <- as.factor(GameData$Symbol)
GameData$Mode <- as.factor(GameData$Mode)
GameData$Term <- as.factor(GameData$Term)
GameData$By <- as.factor(GameData$By)

根据模式的变化,我希望可视化这些传球和目标在时间上的执行情况。但是,当我在ggplot2中将其绘制为水平条形图时,相反的是在适当的时间将时间相加而不是颜色变化。例如,每个术语的最长时间是9分钟,但x轴上升到30?我的情节代码如下:

# Load package
require(ggplot2)
# Plot
ggplot(GameData, aes(x = Term, y = Time, fill = Mode)) +
  geom_bar(stat = "identity") +
  geom_text(data = GameData, aes(label = Symbol, colour = By), size = 9) +
  scale_color_manual(values =c("black", "red")) +
  coord_flip() +
  scale_x_discrete(limits = rev(levels(GameData$Term))) 

我觉得这是一个愚蠢的错误,但我哪里出错,所以颜色/模式在相应的时间发生变化?

总之,我希望下面的图表背景为每个Mode的每个Time提供不同的颜色{/ 1}}。

Term

感谢。

1 个答案:

答案 0 :(得分:1)

这是使用geom_tile()绘制彩色条的部分解决方案(感谢@Gregor的想法)。

# Work around to make sure Time=8 appears on x-axis.
GameData$discrete_time = factor(GameData$Time, levels=paste(1:9))

plot1 = ggplot(GameData, aes(y=Term, x=discrete_time)) +
        geom_tile(aes(fill=Mode)) +
        geom_text(aes(label=Symbol, colour=By), size=9) +
        scale_color_manual(values=c("black", "white")) +
        scale_fill_brewer(palette="Set1") +
        scale_x_discrete(drop=FALSE)

ggsave("plot.png", plot=plot1, width=9, height=3, dpi=150)

enter image description here

评论:

  • 您可以通过在数据中添加适当的行来填充空白图块(将符号设置为NA以为图块着色,但将通行证/目标留空)。
  • 有一些位置(例如,Term = 1,Time = 1),其中有两个'Passes'完全重叠。我尝试了各种躲避,抖动,分组策略,但没有什么看起来很好,并揭示了重叠的事件。如果扩展到更大的数据集,解决此问题将变得更加重要。
相关问题