gpt4 book ai didi

r - 如何使用ggplot2绘制表格

转载 作者:行者123 更新时间:2023-12-05 04:07:06 25 4
gpt4 key购买 nike

我有一个西甲足球比赛的数据框,我想制作一个表格,其中每一行和每一列都是一个球队名称,每个图 block 显示两队比赛的结果

我已经尝试过以许多不同的方式使用 geom_tileggplot2 但我最接近的是下面的代码

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")

我需要按奇数对行进行着色(奇数行白色,偶数行蓝色)我还希望团队名称位于图 block 内总而言之,我希望我的 table 看起来像第一张照片 here但有条纹

谁能帮我修改我的代码?

最佳答案

您可以通过为填充指定一个新因子来更改行颜色。考虑例如这个

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

为了在图 block 中包含轴标签,您必须扩展轴(因为它是分类的,再次通过指定其他因素),想想 this - 但是你最好只使用 Rmarkdown 或 HTML 等等

关于r - 如何使用ggplot2绘制表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48977680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com