R条形图更改

时间:2017-03-08 00:22:16

标签: r ggplot2

我正在尝试对图表进行以下更改:

(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 个答案:

答案 0 :(得分:2)

(1)以标题为中心,将plot.title = element_text(hjust = 0.5)添加到主题

(2)添加labs(y = "Average\n(Per game)")以添加y轴的标签。 &#34; \ n&#34;打破界限。

(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)")  

答案 1 :(得分: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

相关问题