2017-03-08 46 views
1

我想對圖形進行以下更改:R條形圖變化

(1)我想爲居中的圖形標題。當我嘗試添加標題時,它位於左側。 (2)我想Y軸標籤有多個單詞。即「平均(每場遊戲)」。每次我有多個單詞時,圖形都會完全改變。如果可能,我還希望「平均」和「(每場比賽)」在不同的路線上。

(3)我想圖的背景是灰色的,但是有白色的網格線。

任何幫助將不勝感激!

df <- read.table(textConnection(
    'Statistic Warm Avg Cold 
    HR(Away) 1.151 1.028 .841 
    HR(Home) 1.202 1.058 .949 
    BB(Away) 3.205 3.269 3.481 
    BB(Home) 3.286 3.367 3.669 
    Runs(Away) 4.909 4.591 4.353 
    Runs(Home) 5.173 4.739 4.608'), header = TRUE) 

library(dplyr) 
library(tidyr) 
library(ggplot2) 

df %>% 
    gather(Temperature, Average, -Statistic) %>% 
    mutate(Temperature = factor(Temperature, c("Cold", "Avg", "Warm"))) %>% 
    ggplot(aes(x=Statistic, y=Average)) + 
    geom_col(aes(fill = Temperature), position = "dodge") + 
    scale_fill_manual(values = c("blue", "yellow", "red"))+ 
    theme_bw() + 
    theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) 

回答

2

(1)爲了使標題居中添加plot.title = element_text(hjust = 0.5)的主題

(2)添加labs(y = "Average\n(Per game)")以添加標籤爲y軸。 「\ n」打破了這條線。

(3)最簡單的解決方案是刪除theme_bw。另外,檢查出http://docs.ggplot2.org/dev/vignettes/themes.html

df <- read.table(textConnection(
    'Statistic Warm Avg Cold 
    HR(Away) 1.151 1.028 .841 
    HR(Home) 1.202 1.058 .949 
    BB(Away) 3.205 3.269 3.481 
    BB(Home) 3.286 3.367 3.669 
    Runs(Away) 4.909 4.591 4.353 
    Runs(Home) 5.173 4.739 4.608'), header = TRUE) 

library(dplyr) 
library(tidyr) 
library(ggplot2) 

df %>% 
    gather(Temperature, Average, -Statistic) %>% 
    mutate(Temperature = factor(Temperature, c("Cold", "Avg", "Warm"))) %>% 
    ggplot(aes(x=Statistic, y=Average)) + 
    geom_bar(aes(fill = Temperature), stat='identity', position = "dodge") + 
    scale_fill_manual(values = c("blue", "yellow", "red"))+ 
    theme(axis.title.y = element_text(angle = 0, vjust = 0.5), 
     plot.title = element_text(hjust = 0.5)) + 
    labs(title = "Title", y = "Average\n(Per game)") 
+0

謝謝!它看起來就是我想要的。 –

1

NBATreands的回答是完美的,這就是我的回答:

df %>% 
    gather(Temperature, Average, -Statistic) %>% 
    mutate(Temperature = factor(Temperature, c("Cold", "Avg", "Warm"))) %>% 
    ggplot(aes(x=Statistic, y=Average)) + 
    ggtitle("This is the title") + 
    ylab("Average\n(Per game)") + 
    geom_col(aes(fill = Temperature), position = "dodge") + 
    scale_fill_manual(values = c("blue", "yellow", "red"))+ 
    theme(
    plot.title = element_text(hjust=0.5), 
    axis.title.y = element_text(angle = 0, vjust = 0.5), 
    panel.background = element_rect(fill = "gray"), 
    panel.grid = element_line(colour = "white") 
    ) 

結果情節是: enter image description here

+0

我喜歡背景中深灰色的陰影! –