0

I was trying to insert the sd bars in geom_point in a data of decomposition rates of different time observations and species using the code below. My data have two factors time and specie and the varable "rem". I used the aggregate function to group species and time and I used the function to calculate the means and sd results of each specie in each time observation. After that I used the geom_errorbar function to insert the sd bars. But appears an Error in geom_errorbar():

`#remanescente
> library(ggplot2)
> # Calcular o desvio padrão para cada combinação de espécie e tempo
> dados_summary <- aggregate(rem ~ tempo + especie, data = df,
+                            FUN = function(rem) c(media = mean(rem), desvio = sd(rem)))
> dados_summary
   tempo                    especie   rem.media  rem.desvio
1      0         Brosimum guianense 1.000000000 0.000000000
2     15         Brosimum guianense 0.825000000 0.077781746
3     30         Brosimum guianense 0.453333333 0.015275252
4     45         Brosimum guianense 0.443333333 0.005773503
5     90         Brosimum guianense 0.650000000 0.028284271
6    135         Brosimum guianense 0.180000000 0.028284271
7    180         Brosimum guianense 0.196666667 0.035118846
8    225         Brosimum guianense 0.185000000 0.035355339
9    270         Brosimum guianense 0.196666667 0.057735027
10   315         Brosimum guianense 0.160000000 0.020000000
11     0         Dialium guianensis 1.000000000 0.000000000
12    15         Dialium guianensis 0.733333333 0.046188022
13    30         Dialium guianensis 0.605000000 0.063639610
14    45         Dialium guianensis 0.420000000 0.014142136
15    90         Dialium guianensis 0.440000000 0.040000000
16   135         Dialium guianensis 0.436666667 0.046188022
17   180         Dialium guianensis 0.330000000 0.042426407
18   225         Dialium guianensis 0.260000000 0.084852814
19   270         Dialium guianensis 0.333333333 0.028867513
20   315         Dialium guianensis 0.323333333 0.056862407
21     0     Helicostylis tomentosa 1.000000000 0.000000000
22    15     Helicostylis tomentosa 0.803333333 0.068068593
23    30     Helicostylis tomentosa 0.723333333 0.075718778
24    45     Helicostylis tomentosa 0.560000000 0.042426407
25    90     Helicostylis tomentosa 0.530000000 0.121243557
26   135     Helicostylis tomentosa 0.533333333 0.115902258
27   180     Helicostylis tomentosa 0.435000000 0.021213203
28   225     Helicostylis tomentosa 0.465000000 0.035355339
29   270     Helicostylis tomentosa 0.340000000 0.017320508
30   315     Helicostylis tomentosa 0.290000000 0.036055513
31     0         Mabea occidentalis 1.000000000 0.000000000
32    15         Mabea occidentalis 0.645000000 0.007071068
33    30         Mabea occidentalis 0.675000000 0.106066017
34    45         Mabea occidentalis 0.315000000 0.091923882
35    90         Mabea occidentalis 0.436666667 0.046188022
36   135         Mabea occidentalis 0.433333333 0.057735027
37   180         Mabea occidentalis 0.370000000 0.000000000
38   225         Mabea occidentalis 0.290000000 0.056568542
39   270         Mabea occidentalis 0.196666667 0.015275252
40   315         Mabea occidentalis 0.193333333 0.050332230
41     0             Parkia pendula 1.000000000 0.000000000
42    15             Parkia pendula 0.995000000 0.007071068
43    30             Parkia pendula 0.880000000 0.040000000
44    45             Parkia pendula 0.713333333 0.040414519
45    90             Parkia pendula 0.585000000 0.021213203
46   135             Parkia pendula 0.226666667 0.065064071
47   180             Parkia pendula 0.176666667 0.070237692
48   225             Parkia pendula 0.060000000 0.000000000
49   270             Parkia pendula 0.055000000 0.021213203
50   315             Parkia pendula 0.086666667 0.040414519
51     0       Pouteria grandiflora 1.000000000 0.000000000
52    15       Pouteria grandiflora 0.790000000 0.052915026
53    30       Pouteria grandiflora 0.743333333 0.005773503
54    45       Pouteria grandiflora 0.625000000 0.007071068
55    90       Pouteria grandiflora 0.653333333 0.144337567
56   135       Pouteria grandiflora 0.646666667 0.115036226
57   180       Pouteria grandiflora 0.503333333 0.080829038
58   225       Pouteria grandiflora 0.440000000 0.017320508
59   270       Pouteria grandiflora 0.413333333 0.015275252
60   315       Pouteria grandiflora 0.406666667 0.080829038
61     0        Tapirira guianensis 1.000000000 0.000000000
62    15        Tapirira guianensis 0.940000000 0.017320508
63    30        Tapirira guianensis 0.155000000 0.007071068
64    45        Tapirira guianensis 0.063333333 0.011547005
65    90        Tapirira guianensis 0.056666667 0.015275252
66   135        Tapirira guianensis 0.053333333 0.023094011
67   180        Tapirira guianensis 0.050000000 0.010000000
68   225        Tapirira guianensis 0.050000000 0.010000000
69   270        Tapirira guianensis 0.016666667 0.005773503
70   315        Tapirira guianensis 0.016666667 0.005773503
71     0 Thyrsodium schomburgkianum 1.000000000 0.000000000
72    15 Thyrsodium schomburgkianum 0.940000000 0.010000000
73    30 Thyrsodium schomburgkianum 0.930000000 0.050000000
74    45 Thyrsodium schomburgkianum 0.820000000 0.103923048
75    90 Thyrsodium schomburgkianum 0.660000000 0.042426407
76   135 Thyrsodium schomburgkianum 0.756666667 0.057735027
77   180 Thyrsodium schomburgkianum 0.755000000 0.035355339
78   225 Thyrsodium schomburgkianum 0.575000000 0.134350288
79   270 Thyrsodium schomburgkianum 0.455000000 0.049497475
80   315 Thyrsodium schomburgkianum 0.573333333 0.056862407
> str(dados_summary)
'data.frame':   80 obs. of  3 variables:
 $ tempo  : Factor w/ 10 levels "0","15","30",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ especie: Factor w/ 8 levels "Brosimum guianense",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ rem    : num [1:80, 1:2] 1 0.825 0.453 0.443 0.65 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:2] "media" "desvio"
> # Criar o gráfico de dispersão com cores diferentes para cada espécie e desvio padrão
> ggplot() +
+   geom_point(data = dados, aes(x = tempo, y = rem, color = especie, group = especie, shape = especie), size = 3) +
+   geom_line(data = dados, aes(x = tempo, y = rem, group = especie), size = 1) +
+   geom_errorbar(data = dados_summary, aes(x = tempo, ymin = rem - sd, ymax = rem + sd, color = especie, group = especie), width = 0.2) +
+   labs(x = "Time (days)", y = "Mass remaining") +
+   ggtitle("") +
+   theme_bw() +
+   theme(
+     plot.background = element_rect(fill = "white"),
+     panel.grid.major = element_blank(),
+     panel.grid.minor = element_blank(),
+     text = element_text(color = "black"),
+     legend.text = element_text(face = "italic")  # Aplicar itálico ao texto da legenda
+   ) +
+   scale_y_continuous(labels = scales::percent, limits = c(0, 1.1), breaks = seq(0, 1., by = 0.250), expand = c(0, 0)) +
+   scale_x_continuous(breaks = c(15, 30, 45, 90, 135, 180, 225, 270, 315), expand = c(0, 0), limits = c(0, 330)) +
+   scale_color_manual(values = c("Brosimum guianense" = "red", 
+                                 "Dialium guianensis" = "blue", 
+                                 "Helicostylis tomentosa" = "green", 
+                                 "Mabea occidentalis" = "orange", 
+                                 "Parkia pendula" = "purple", 
+                                 "Pouteria grandiflora" = "gray", 
+                                 "Tapirira guianensis" = "black", 
+                                 "Thyrsodium schomburgkianum" = "brown")) +
+   scale_shape_manual(values = c("Brosimum guianense" = 16, 
+                                 "Dialium guianensis" = 17, 
+                                 "Helicostylis tomentosa" = 18, 
+                                 "Mabea occidentalis" = 19, 
+                                 "Parkia pendula" = 20, 
+                                 "Pouteria grandiflora" = 21, 
+                                 "Tapirira guianensis" = 22, 
+                                 "Thyrsodium schomburgkianum" = 23)) +
+   guides(shape = guide_legend(override.aes = list(size = 4)),
+          color = guide_legend(override.aes = list(title = NULL))) +
+   labs(color = NULL, shape = NULL)
Error in `geom_errorbar()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `rem - sd`:
! non-numeric argument to binary operator
Run `rlang::last_trace()` to see where the error occurred.
> rlang::last_trace()
<error/rlang_error>
Error in `geom_errorbar()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `rem - sd`:
! non-numeric argument to binary operator
---
Backtrace:
     ▆
  1. ├─base (local) `<fn>`(x)
  2. └─ggplot2:::print.ggplot(x)
  3.   ├─ggplot2::ggplot_build(x)
  4.   └─ggplot2:::ggplot_build.ggplot(x)
  5.     └─ggplot2:::by_layer(...)
  6.       ├─rlang::try_fetch(...)
  7.       │ ├─base::tryCatch(...)
  8.       │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
  9.       │ │   └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
 10.       │ │     └─base (local) doTryCatch(return(expr), name, parentenv, handler)
 11.       │ └─base::withCallingHandlers(...)
 12.       └─ggplot2 (local) f(l = layers[[i]], d = data[[i]])
 13.         └─l$compute_aesthetics(d, plot)
 14.           └─ggplot2 (local) compute_aesthetics(..., self = self)
 15.             └─base::lapply(aesthetics, eval_tidy, data = data, env = env)
 16.               └─rlang (local) FUN(X[[i]], ...)
Run rlang::last_trace(drop = FALSE) to see 5 hidden frames.
rlang::last_trace(drop = FALSE)
<error/rlang_error>
Error in `geom_errorbar()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `rem - sd`:
! non-numeric argument to binary operator
---
Backtrace:
     ▆
  1. ├─base (local) `<fn>`(x)
  2. ├─ggplot2:::print.ggplot(x)
  3. │ ├─ggplot2::ggplot_build(x)
  4. │ └─ggplot2:::ggplot_build.ggplot(x)
  5. │   └─ggplot2:::by_layer(...)
  6. │     ├─rlang::try_fetch(...)
  7. │     │ ├─base::tryCatch(...)
  8. │     │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
  9. │     │ │   └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
 10. │     │ │     └─base (local) doTryCatch(return(expr), name, parentenv, handler)
 11. │     │ └─base::withCallingHandlers(...)
 12. │     └─ggplot2 (local) f(l = layers[[i]], d = data[[i]])
 13. │       └─l$compute_aesthetics(d, plot)
 14. │         └─ggplot2 (local) compute_aesthetics(..., self = self)
 15. │           └─base::lapply(aesthetics, eval_tidy, data = data, env = env)
 16. │             └─rlang (local) FUN(X[[i]], ...)
 17. └─base::.handleSimpleError(...)
 18.   └─rlang (local) h(simpleError(msg, call))
 19.     └─handlers[[1L]](cnd)
 20.       └─cli::cli_abort(...)
 21.         └─rlang::abort(...)`

stefan
  • 90,330
  • 6
  • 25
  • 51
Ane Fortes
  • 11
  • 1
  • 2
    Hi Ane. Could you please format you code properly? As is it looks like you simply copied the output and code from the console. Instead copy the code from your script. Also, to share your data have a look at the options described in [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – stefan May 07 '23 at 18:59

1 Answers1

0

When posting a question, its always best to provide a small reproducible example. With that being said, I think your issue is that you're mixing your references to the original dataset and the summary one. I think you need something like this:

library(tidyverse)

dados |>
  group_by(tempo, especie)|>
  summarize(media = mean(rem),
            desvio = sd(rem)) |>
  ggplot()|>
  geom_point(aes(x = tempo, y = mean, color = especie, 
                 group = especie, shape = especie), size = 3) +
  geom_line(aes(x = tempo, y = mean, group = especie), size = 1) +
  geom_errorbar(aes(x = tempo, ymin = mean - sd, ymax = mean + sd, 
                    color = especie, group = especie), width = 0.2) +
  labs(x = "Time (days)", y = "Mass remaining") +
  ggtitle("") +
  theme_bw() +
  theme(
    plot.background = element_rect(fill = "white"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    text = element_text(color = "black"),
    legend.text = element_text(face = "italic")  # Aplicar itálico ao texto da legenda
    ) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 1.1), 
                     breaks = seq(0, 1., by = 0.250), expand = c(0, 0)) +
  scale_x_continuous(breaks = c(15, 30, 45, 90, 135, 180, 225, 270, 315), 
                     expand = c(0, 0), limits = c(0, 330)) +
  scale_color_manual(values = c("Brosimum guianense" = "red",                       
                                "Dialium guianensis" = "blue", 
                                "Helicostylis tomentosa" = "green", 
                                "Mabea occidentalis" = "orange", 
                                "Parkia pendula" = "purple", 
                                "Pouteria grandiflora" = "gray", 
                                "Tapirira guianensis" = "black", 
                                "Thyrsodium schomburgkianum" = "brown")) +
  scale_shape_manual(values = c("Brosimum guianense" = 16, 
                                "Dialium guianensis" = 17, 
                                "Helicostylis tomentosa" = 18, 
                                "Mabea occidentalis" = 19, 
                                "Parkia pendula" = 20, 
                                "Pouteria grandiflora" = 21, 
                                "Tapirira guianensis" = 22, 
                                "Thyrsodium schomburgkianum" = 23)) +
  guides(shape = guide_legend(override.aes = list(size = 4)),
         color = guide_legend(override.aes = list(title = NULL))) +
  labs(color = NULL, shape = NULL)
AndS.
  • 7,748
  • 2
  • 12
  • 17