每个月(1月至12月)并排显示四个变量的条形图

时间:2018-06-01 17:20:40

标签: r ggplot2

我是R的首发,我想在1月至12月期间绘制两年内降雨和太阳辐射数据的条形图(附加数据)。

要绘制的数据:

enter image description here

我正在尝试绘制第一行(1月),但我收到此错误

  

-0.01 * height中的错误:二元运算符的非数字参数

如何处理?以及用于绘制数据的脚本?

此致

1 个答案:

答案 0 :(得分:0)

这是一个例子

library(tidyverse)

set.seed(123456)

df <- data.frame(Month = month.abb,
                 R_2014 = runif(n = 12, min = 0, max = 195),
                 R_2015 = runif(n = 12, min = 0, max = 295),
                 S_2014 = runif(n = 12, min = 3, max = 10),
                 S_2015 = runif(n = 12, min = 4, max = 10))
df
#>    Month    R_2014    R_2015   S_2014   S_2015
#> 1    Jan 155.56794 267.06645 6.344445 9.714178
#> 2    Feb 146.94519 259.85035 7.903533 9.229704
#> 3    Mar  76.29486 293.18178 9.159223 8.272923
#> 4    Apr  66.60356 264.30712 9.144556 7.632427
#> 5    May  70.45235 259.19979 8.977157 5.352593
#> 6    Jun  38.67722  58.29370 4.161913 8.437571
#> 7    Jul 104.29730  98.82311 6.660781 9.373255
#> 8    Aug  18.82262 229.27586 9.083897 5.766779
#> 9    Sep 192.63015  47.08010 4.618097 7.092115
#> 10   Oct  32.67605  23.79035 3.833566 6.607897
#> 11   Nov 155.60788  39.13185 8.767659 7.450991
#> 12   Dec 115.78983  50.71209 3.561939 8.445736

# convert from wide to long format
# separate columns to get variable and year
df_long <- df %>% 
  gather(key, value, -Month) %>% 
  separate(key, into = c("variable", "Year"), "_") %>% 
  mutate(Month = factor(Month, levels = month.abb))
head(df_long)
#>   Month variable Year     value
#> 1   Jan        R 2014 155.56794
#> 2   Feb        R 2014 146.94519
#> 3   Mar        R 2014  76.29486
#> 4   Apr        R 2014  66.60356
#> 5   May        R 2014  70.45235
#> 6   Jun        R 2014  38.67722

# facet by year
plt1 <- ggplot(df_long, aes(x = Month, y = value, fill = variable)) +
  geom_col(position = "dodge") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  facet_wrap(~ Year)
plt1

# facet by variable
plt2 <- ggplot(df_long, aes(x = Month, y = value, fill = Year)) +
  geom_col(position = "dodge") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  facet_wrap( ~ variable, scales = "free_y")
plt2

reprex package(v0.2.0)创建于2018-06-01。