简体   繁体   中英

R Stacked Bar Plot for Baseball Statistics

I am trying to make a plot similar to the picture attached. Except I want 'Cut' as 'Stat', 'Diamond Color Classes' as 'Team', and 'Count' as 'Value'. I think the data frame setup in the long piece of code is the correct version, but I also tried this:

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)

Any help fixing this issue would be much appreciated.

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

在此处输入图片说明

I believe this is what you are looking for. I used the data in the second part of your post (the longer one):

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

在此处输入图片说明

You needed to add a y aesthetic and stat = "identity" so it will stack. Note I removed all the extra formatting to highlight my changes but that can easily be added back in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM