0

I am a starter in R and would like to plot a bar chart of my rainfall and solar radiation data of two years side by side from January to December (attached data).

data to plot:

enter image description here

I am trying to plot the first row (January) but I am getting this error

Error in -0.01 * height : non-numeric argument to binary operator

How to deal with that? and and which script to use to get my data plotted?

Regards,

Tung
  • 26,371
  • 7
  • 91
  • 115
Gabriel
  • 11
  • 1
  • 2
    Can you share the code you're using? Also, if you're importing data from excel, make sure the `class` for the data columns is numeric and not char. – iod Jun 01 '18 at 17:26
  • 4
    Please read [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and update your question. – Nathan Werth Jun 01 '18 at 17:35

1 Answers1

0

Here is an example

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

Created on 2018-06-01 by the reprex package (v0.2.0).

Tung
  • 26,371
  • 7
  • 91
  • 115