2017-05-04 191 views
1

我正在嘗試繪製類似於所附圖片的繪圖。除了我想'剪切'爲'統計','鑽石顏色類'爲'團隊','計數'爲'價值'。我認爲在漫長的一段代碼的數據幀的設置是正確的版本,但我也試過這樣:R用於棒球統計的堆積條形圖

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

回答

2

我相信這是你在找什麼。我使用的數據在您的文章(較長的一個)的第二部分:

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

enter image description here

您需要添加一個y審美和stat = "identity"所以它會疊加。注意我刪除了所有額外的格式以突出顯示我的更改,但可以輕鬆地將其重新添加。

+0

非常感謝!我嘗試了y = Value,但得到一個錯誤,因爲我沒有stat =「identity」。 –

+0

沒問題,樂意幫忙! –