我正在尝试使用 R 中的一些 ggplots 对最近的 MLB 草案进行一些分析
selection <- draft[c("Team","Division","Position")]
head(selection)
Team Division Position
1 pit NL Central P
2 sea AL West P
3 ari NL West P
4 bal AL East P
5 kc AL Central O
6 was NL East I
其中 P = 投手,O = 外场等。
我想按每个分区内的位置显示团队选择的球员数量
p <- ggplot(data=selection, aes(x=Team, fill= Position)) + geom_bar(position="stack")
p <- p + coord_flip()
p <- p+ ylab("Players Selected")
p <- p + facet_wrap(~Division)
p
这让我成为了那里的一部分,但非常没有吸引力
a) 分组有效,但所有团队都显示在每个分区网格中 - 即使每个分区中只有 5 或 6 个团队实际上 - 并且正确地 - 显示数据
b) 通过 co-ord 翻转,团队按倒序字母顺序向下列出。我可以诉诸。留下理由也很好
c) 我如何将图例设置为 Pitching, Outfield 而不是 P 和 O - 这是我需要设置和包含的向量吗
d) 看到每个球队选择对每种类型球员的比例也很有趣。这是通过设置 position="fill"来实现的。我可以将轴设置为 % 而不是 0 到 1。我还尝试设置 geom_vline(aes(xintercept=0.5) -and yintercept,以防翻转因素 -
但这条线没有出现在沿 x 轴的中间标记处
非常感谢帮助
最佳答案
编辑 :在抓取数据(并将其存储在名为 mlbtmp.txt
的文本文件中)和一些更多实验之后,完成改造,包括来自其他答案的信息:
selection <- read.table("mlbtmp.txt",skip=1)
names(selection) <- c("row","League","Division","Position","Team")
## arrange order/recode factors
selection <- transform(selection,
Team=factor(Team,levels=rev(levels(Team))),
Position=factor(Position,levels=c("P","I","C","O"),
labels=c("Pitching","Infield",
"Center","Outfield")))
我玩弄了
facet_grid
的各种排列, facet_wrap
, scales
, coord_flip
等。有些按预期工作,有些没有:library(ggplot2)
p <- ggplot(data=selection, aes(x=Team, fill= Position)) +
geom_bar(position="stack")
p + facet_grid(.~Division,scales="free_x") + coord_flip() ## OK
## seems to fail with either "free_x" or "free_y"
p + facet_grid(Division~.,scales="free") + coord_flip()
## works but does not preserve 'count' axis:
p + facet_wrap(~Division,scales="free")
我最终得到了
facet_wrap(...,scales="free")
并使用 ylim
来约束轴。p + facet_wrap(~Division,scales="free") + coord_flip() +
ylim(0,60) + opts(axis.text.y=theme_text(hjust=0))
原则上可能有一种方法可以使用
..density..
, ..ncount..
, ..ndensity..
,或由 stat_bin
计算的其他统计信息之一而不是默认 ..count..
,但我找不到有效的组合。相反(当坚持使用 ggplot 的即时转换时,这通常是最好的解决方案)我自己 reshape 了数据:
## pull out Team identification within Division and League
stab <- unique(subset(selection,select=c(Team,Division,League)))
## compute proportions by team
s2 <- melt(ddply(selection,"Team",function(x) with(x,table(Position)/nrow(x))))
## fix names
s2 <- rename(s2,c(variable="Position",value="proportion"))
## merge Division/League info back to summarized data
s3 <- merge(s2,stab)
p2 <- ggplot(data=s3, aes(x=Team, fill= Position,y=proportion)) +
geom_bar(position="stack")+scale_y_continuous(formatter="percent")+
geom_hline(yintercept=0.5,linetype=3)+ facet_wrap(~Division,scales="free") +
opts(axis.text.y=theme_text(hjust=0))+coord_flip()
显然这里可以做一些更漂亮的事情,但这应该可以让你完成大部分工作......
关于r - 自定义多面条形图的美学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297677/