用于棒球统计的R堆积条形图

时间:2017-05-04 17:07:12

标签: r ggplot2 geom-bar

我正在尝试制作类似于附图的情节。除了我希望'Cut'为'Stat','Diamond Color Classes'为'Team','Count'为'Value'。我认为长代码中的数据框设置是正确的版本,但我也试过了:

df <- read.table(textConnection(
  'Team Runs    Doubles Triples Homers  Walks
  Redsox    878 343 25  208 558
  Cubs  808 293 30  199 656
  Phillies  610 231 35  161 424
  Twins 722 288 35  200 513
  Dodgers   725 272 21  189 525'), header = TRUE)

非常感谢您解决此问题的任何帮助。

df <- read.table(textConnection(
  'Stat Team    Value
  Runs  Redsox  878
  Runs  Cubs    808
  Runs  Phillies    610
  Runs  Twins   722
  Runs  Dodgers 725
  Doubles   Redsox  343
  Doubles   Cubs    293
  Doubles   Phillies    231
  Doubles   Twins   288
  Doubles   Dodgers 272
  Triples   Redsox  25
  Triples   Cubs    30
  Triples   Phillies    35
  Triples   Twins   35
  Triples   Dodgers 21
  Homers    Redsox  208
  Homers    Cubs    199
  Homers    Phillies    161
  Homers    Twins   200
  Homers    Dodgers 189
  Walks Redsox  558
  Walks Cubs    656
  Walks Phillies    424
  Walks Twins   513
  Walks Dodgers 525'), header = TRUE)



library(ggplot2)

hw <- theme_gray()+ theme(
  plot.title=element_text(hjust=0.5),
  plot.subtitle=element_text(hjust=0.5),
  plot.caption=element_text(hjust=-.5),

  strip.text.y = element_blank(),
  strip.background=element_rect(fill=rgb(.9,.95,1),
                                colour=gray(.5), size=.2),

  panel.border=element_rect(fill=FALSE,colour=gray(.70)),
  panel.grid.minor.y = element_blank(),
  panel.grid.minor.x = element_blank(),
  panel.spacing.x = unit(0.10,"cm"),
  panel.spacing.y = unit(0.05,"cm"),

  axis.ticks=element_blank(),
  axis.text=element_text(colour="black"),
  axis.text.y=element_text(margin=margin(0,3,0,3)),
  axis.text.x=element_text(margin=margin(-1,0,3,0))
)


ggplot(df,aes(x=Team,fill=Stat))+
  geom_bar(color=gray(.55)) + 
  labs(x="Team",
       y="Value",
       title="Baseball Team Stats (2016)",
       fill="Stat")+
  scale_fill_manual(
    values=c("red","blue",rgb(0,.8,0),'cyan','violet'),
    na.value="grey30")+ hw

enter image description here

1 个答案:

答案 0 :(得分:2)

我相信这就是你要找的东西。我使用了帖子第二部分中的数据(较长的一部分):

ggplot(df,aes(x=Team, y = Value, fill=Stat))+
  geom_bar(color=gray(.55), stat = "identity") 

enter image description here

您需要添加y美学和stat = "identity",以便它会叠加。注意我删除了所有额外的格式以突出显示我的更改,但可以轻松地重新添加。