Re: [R] ggplot 3-dimensions

2023-12-17 Thread SIBYLLE STÖCKLI via R-help
Dear R community

In the meantime I made some progress:
  ggplot(data = Fig2b, aes(x = BFF, y = Wert, fill = Effekt))+theme_bw()+ 
geom_bar(stat = "identity", width = 0.95) +
scale_y_continuous(limits=c(0,13), expand=c(0,0))+
facet_wrap(~Aspekt, strip.position = "bottom", scales = "free_x") +
theme(panel.spacing = unit(0, "lines"), 
  strip.background = element_blank(),
  strip.placement = "outside")+
theme(axis.title.x=element_blank())+
scale_fill_manual("Effekt", values = c("Neg" = "red", "Neu" =
"darkgrey", "Pos" = "blue"), labels=c("Negativ", "Nicht sign.", "Positiv"))
  
  
Question
- Is it possible to present all the subpolots in one graph (not to "lines")?

- I tried to change the angel of the x-axis. However, I was able to change
the first x-axis (BB...), but not the second one (Voegel). Maybe this
would solve the problem.
- If not, is there another possibility to fix the number of subplots per
line?

Kind regards
Sibylle

-Original Message-
From: R-help  On Behalf Of SIBYLLE STÖCKLI via
R-help
Sent: Saturday, December 16, 2023 12:16 PM
To: R-help@r-project.org
Subject: [R] ggplot 3-dimensions

Dear R-user

Does anybody now, if ggplot allows to use two x-axis including two
dimensions (similar to excel plot (picture 1 in the pdf attachmet). If yes,
how should I adapt my code? The parameters are presented in the input file
(attachment: Input).

Fig2b = read.delim("BFF_Fig-2b.txt", na.strings="NA")
names(Fig2b)
head(Fig2b)
summary(Fig2b)
str(Fig2b)
Fig2b$Aspekt<-factor(Fig2b$Aspekt, levels=(c("Voegel", "Kleinsaeuger",
"Schnecken", "Regenwuermer_Asseln", "Pilze")))

### Figure 2b
  ggplot(Fig2b,aes(Aspekt,Wert,fill=Effekt))+
geom_bar(stat="identity",position='fill')+
scale_y_continuous(limits=c(0,14), expand=c(0,0))+
labs(x="", y="Anzahl Studien pro Effekt")

Kind regards
Sibylle



ggplot_3dim.pdf
Description: Adobe PDF document
__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] ggarrange & legend

2024-02-05 Thread SIBYLLE STÖCKLI via R-help
Dear R community

It is possible to adjust the legend in combined ggplots using ggarrange with
be positions top, bottom, left and right.
My question: Is there a function to change the position of the legend to
topright or bottomleft? Right and top etc are in the middle of the axis.

Kind regards
Sibylle

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] ggarrange & legend

2024-02-05 Thread SIBYLLE STÖCKLI via R-help
Dear John Kane

Dear R community

 

Here my working example

1.  Example that is working with legend=”top”. However, as mentioned, the 
legend is in the middle of the top axis. 

mylist<-list(p1, p2)

dev.new(width=28, height=18)

fig1<- ggarrange(plotlist=mylist, common.legend = TRUE, legend="top", labels = 
c("(A)", "(B)"), font.label = list(size = 18, color = "black"), ncol=2)

fig1

 

2.  My question is how I can position the legend on the topright of the top 
axis. However, “topright” is not a common label for legend in ggarrange (but in 
other plot functions), so legend =”topright” is not working.

mylist<-list(p1, p2)

dev.new(width=28, height=18)

fig1<- ggarrange(plotlist=mylist, common.legend = TRUE, legend="topright", 
labels = c("(A)", "(B)"), font.label = list(size = 18, color = "black"), ncol=2)

fig1

 

Kind regards

Sibylle

 

From: John Kane  
Sent: Monday, February 5, 2024 1:59 PM
To: sibylle.stoec...@gmx.ch
Cc: r-help@r-project.org
Subject: Re: [R] ggarrange & legend

 

Could you supply us with a MWE (minimal working example)of what you have so far?

Thanks.

 

On Mon, 5 Feb 2024 at 05:00, SIBYLLE STÖCKLI via R-help mailto:r-help@r-project.org> > wrote:

Dear R community

It is possible to adjust the legend in combined ggplots using ggarrange with
be positions top, bottom, left and right.
My question: Is there a function to change the position of the legend to
topright or bottomleft? Right and top etc are in the middle of the axis.

Kind regards
Sibylle

__
R-help@r-project.org <mailto:R-help@r-project.org>  mailing list -- To 
UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



-- 

John Kane
Kingston ON Canada


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] igraph_vertex

2024-02-24 Thread SIBYLLE STÖCKLI via R-help
Dear R-community

 

It would be nice to get some input how to find a solution for the following
error in igraph and vertex setting.

 

Thank you very much

Sibylle

 

> par(bg="black")

> network %>% plot(

+ vertex.color=clrs[V(.)$community], 

+ vertex.size=V(.)$hub_score*1, 

+ vertex.frame.color=V(.)$color, 

+ vertex.label.color="white", 

+ vertex.label.cex=0.5, 

+ vertex.label.family="Helvetica",

+ vertex.label.font=1,

+ edge.curved=0.5,

+ edge.width= network,

+ layout=layout_with_mds(.))

Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) : 

  Index gr��er als maximales 6

 

 

Reproducible example:

 

edge_list<-read.csv("edges_table_Test.csv")

 

#create network and add some necessary attributes (vertices) for the plot

network <- graph_from_data_frame(aes_collapsed, directed= FALSE, 

 vertices = details)

 

 

temp<-cluster_optimal(network)

temp<-cbind(membership=temp$membership, Names=temp$name)

aes_collapsed <- aes_collapsed %>%

  merge(temp, by="Names")

 

 

network <- network %>%

  set_edge_attr(name = "type", value = factor(aes_collapsed$Names, 

 ordered =
is.ordered(V(network)$name))) %>%

  set_edge_attr(name = "membership", value = aes_collapsed$membership) %>%

  set_edge_attr(name = "color", 

  value = c(viridis::viridis(5))

  [match(E(.)$type, c(factor(V(.)$name)))]) %>%

  set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type =
"local"))) %>%

  set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) %>%

  set_vertex_attr(name = "color", 

  value = c(viridis::viridis((5)))

  [match(V(.)$name, c(factor(V(.)$name)))]) %>%

  set_vertex_attr(name= "community", value=cluster_optimal(.)$membership)

 

clrs<-scico(3, palette = "batlow")

 

par(bg="black")

network %>% plot(

 vertex.color=clrs[V(.)$community], 

 vertex.size=V(.)$hub_score*5, 

 vertex.frame.color=V(.)$color, 

 vertex.label.color="white", 

 vertex.label.cex=0.5, 

 vertex.label.family="Helvetica",

 vertex.label.font=1,

 edge.curved=0.5,

 edge.width= network,

 layout=layout_with_mds(.))

 

 

edges_table_Test.csv

 


Names

target

weight


B.B

A.A

4


C.C

A.A

5


D.D

A.A

5


E.E

A.A

5


F.F

A.A

1


C.C

B.B

5


E.E

B.B

1


F.F

B.B

2


A.A

C.C

5


B.B

C.C

1


D.D

C.C

5


E.E

C.C

5


F.F

C.C

3


A.A

D.D

5


B.B

D.D

1


C.C

D.D

5


E.E

D.D

5


F.F

D.D

4


A.A

E.E

5


B.B

E.E

1


C.C

E.E

4


D.D

E.E

5


F.F

E.E

5


A.A

F.F

5


B.B

F.F

1


C.C

F.F

2


D.D

F.F

3


E.E

F.F

4


F.F

F.F

5

 


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] igraph_vertex

2024-02-24 Thread SIBYLLE STÖCKLI via R-help
Dear R-community

It would be nice to get some input how to find a solution for the following 
error in igraph and vertex setting.

Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) : 
  Index größer als maximales 6

Kind regards
Sibylle 

Working example

library(circlize)
library(ggplot2)
library(igraph)
library(tidyverse)
library(RColorBrewer)
library(stringi)
library(scico)
library(plotly)
library(ggraph)

edges_table_Test.csv

Names   target  weight
B.B A.A 4
C.C A.A 5
D.D A.A 5
E.E A.A 5
F.F A.A 1
C.C B.B 5
E.E B.B 1
F.F B.B 2
A.A C.C 5
B.B C.C 1
D.D C.C 5
E.E C.C 5
F.F C.C 3
A.A D.D 5
B.B D.D 1
C.C D.D 5
E.E D.D 5
F.F D.D 4
A.A E.E 5
B.B E.E 1
C.C E.E 4
D.D E.E 5
F.F E.E 5
A.A F.F 5
B.B F.F 1
C.C F.F 2
D.D F.F 3
E.E F.F 4
F.F F.F 5

edge_list<-read.csv("edges_table_Test.csv")

network <- graph_from_data_frame(aes_collapsed, directed= FALSE, 
 vertices = details)


temp<-cluster_optimal(network)
temp<-cbind(membership=temp$membership, Names=temp$name)
aes_collapsed <- aes_collapsed %>%
  merge(temp, by="Names")


network <- network %>%
  set_edge_attr(name = "type", value = factor(aes_collapsed$Names, 
 ordered = 
is.ordered(V(network)$name))) %>%
  set_edge_attr(name = "membership", value = aes_collapsed$membership) %>%
  set_edge_attr(name = "color", 
  value = c(viridis::viridis(5))
  [match(E(.)$type, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type = 
"local"))) %>%
  set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) %>%
  set_vertex_attr(name = "color", 
  value = c(viridis::viridis((5)))
  [match(V(.)$name, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name= "community", value=cluster_optimal(.)$membership)

clrs<-scico(3, palette = "batlow")

par(bg="black")
network %>% plot(
 vertex.color=clrs[V(.)$community], 
 vertex.size=V(.)$hub_score*5, 
 vertex.frame.color=V(.)$color, 
 vertex.label.color="white", 
 vertex.label.cex=0.5, 
 vertex.label.family="Helvetica",
 vertex.label.font=1,
 edge.curved=0.5,
 edge.width= network,
 layout=layout_with_mds(.))

Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) : 
  Index größer als maximales 6


tiff("figures/AES_network_bymembership.tiff", width=1000, height=700, res=120)
network %>%
  ggraph(., layout = "auto")+
  geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10), color=from, 
alpha=0.5)) +
  geom_node_point(aes(size = V(network)$hub_score*200, color= 
as.factor(V(network)$community))) +
  geom_node_text(aes(label =  V(network)$name), size=5, color="white", repel=T)+
  scale_color_scico_d(palette = "batlow")+
  scale_edge_width(range = c(0.2,4))+
  scale_size(range = c(0.5,20)) +
  #scale_edge_color_manual(values = c(scico(21, palette="batlow")))+
  theme(plot.background = element_rect(fill = "black"),
legend.position = "right",
panel.background = element_rect(fill = "black"))
dev.off()

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] igraph_vertex

2024-02-25 Thread SIBYLLE STÖCKLI via R-help
Dear coummunity

Thanks a lot to David and Kimmo. Yes I see now that I need to provide the two 
raw tables. Find here the reproducible example.

Kind regards
Sibylle

# R-labraries
library(circlize)
library(ggplot2)
library(igraph)
library(tidyverse)
library(RColorBrewer)
library(stringi)
library(scico)
library(plotly)
library(ggraph)


# Tables
aes<-read.csv("Test_adjac.csv", row.names = 1)
details<-read.csv("Test_cat.csv")

# Edge table, reorganisation
aes_collapsed<-aes %>%
  rownames_to_column(var='Names') %>%
  tidyr::gather(target, weight, 1:ncol(aes)+1) %>%
  dplyr::filter(weight != 0) %>%
  mutate(weight = ifelse(weight == "-1", 0, weight)) # here 0 = negative values

write.csv(aes_collapsed, "edges_table_Test.csv", row.names = F)
edge_list<-read.csv("edges_table_Test.csv")

# Network attributes
network <- graph_from_data_frame(aes_collapsed, directed= FALSE, 
 vertices = details)


temp<-cluster_optimal(network)
temp<-cbind(membership=temp$membership, Names=temp$name)
aes_collapsed <- aes_collapsed %>%
  merge(temp, by="Names")


network <- network %>%
  set_edge_attr(name = "type", value = factor(aes_collapsed$Names, 
 ordered = 
is.ordered(V(network)$name))) %>%
  set_edge_attr(name = "membership", value = aes_collapsed$membership) %>%
  set_edge_attr(name = "color", 
  value = c(viridis::viridis(5))
  [match(E(.)$type, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type = 
"local"))) %>%
  set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) %>%
  set_vertex_attr(name = "color", 
  value = c(viridis::viridis((5)))
  [match(V(.)$name, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name= "community", value=cluster_optimal(.)$membership)

clrs<-scico(3, palette = "batlow")

par(bg="black")
network %>% plot(
 vertex.color=clrs[V(.)$community], 
 vertex.size=V(.)$hub_score*5, 
 vertex.frame.color=V(.)$color, 
 vertex.label.color="white", 
 vertex.label.cex=0.5, 
 vertex.label.family="Helvetica",
 vertex.label.font=1,
 edge.curved=0.5,
 edge.width= network,
 layout=layout_with_mds(.))

#error
Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) : 
  Index größer als maximales 6

# Test_adjac.csv
A.A B.B C.C D.D E.E F.F
A.A 0   0   5   5   5   5
B.B 4   0   1   1   1   1
C.C 5   5   0   5   4   2
D.D 5   0   5   0   5   3
E.E 5   1   5   5   0   4
F.F 1   2   3   4   5   5

# Test_cat.csv
Names   corresponding-NCP   CategorySubcategory_type
sources.cytosource  Factor
A.A 7   hydrologic attribute"A" A   1
B.B 6, 11   hydrologic attribute"B" B   1
C.C 1, 14, 15, 16, 17, 18   AES intrinsic   "C" C   0
D.D 1, 14, 15, 16, 17, 18   AES intrinsic   "D" D   0
E.E 1, 14, 15, 16, 17, 18   AES intrinsic   "E" E   0
F.F 7   AES material"F" F   0


# edges_tables_Test.csv
Names   target  weight
B.B A.A 4
C.C A.A 5
D.D A.A 5
E.E A.A 5
F.F A.A 1
C.C B.B 5
E.E B.B 1
F.F B.B 2
A.A C.C 5
B.B C.C 1
D.D C.C 5
E.E C.C 5
F.F C.C 3
A.A D.D 5
B.B D.D 1
C.C D.D 5
E.E D.D 5
F.F D.D 4
A.A E.E 5
B.B E.E 1
C.C E.E 4
D.D E.E 5
F.F E.E 5
A.A F.F 5
B.B F.F 1
C.C F.F 2
D.D F.F 3
E.E F.F 4
F.F F.F 5

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] igraph_vertex

2024-02-26 Thread SIBYLLE STÖCKLI via R-help
Dear Kimmo

First of all many thanks for the valuable advice to publish code and csv. 
Noted. 
Yes, "edge.width= E(.)$weight" makes definitively sense.

In the following code, which loads the tiff file, I get the following error
tiff("figures/AES_network_bymembership.tiff", width=1000, height=700, res=120)
Warning message:
In doTryCatch(return(expr), name, parentenv, handler) : Character set family 
not found in the Windows character set database

--> I am unsure if mySQL is the right solution. I have no experience how to 
change mySQL.

Kind regards
Sibylle


tiff("figures/AES_network_bymembership.tiff", width=1000, height=700, res=120)
network %>%
  ggraph(., layout = "auto")+
  geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10), color=from, 
alpha=0.5)) +
  geom_node_point(aes(size = V(network)$hub_score*200, color= 
as.factor(V(network)$community))) +
  geom_node_text(aes(label =  V(network)$name), size=5, color="white", repel=T)+
  scale_color_scico_d(palette = "batlow")+
  scale_edge_width(range = c(0.2,4))+
  scale_size(range = c(0.5,20)) +
  #scale_edge_color_manual(values = c(scico(21, palette="batlow")))+
  theme(plot.background = element_rect(fill = "black"),
legend.position = "right",
panel.background = element_rect(fill = "black"))
dev.off()





-Original Message-

From: R-help  On Behalf Of Kimmo Elo
Sent: Monday, February 26, 2024 8:10 AM
To: r-help@r-project.org
Subject: Re: [R] igraph_vertex


Hi,

a quick additional note: try

"edge.width= E(.)$weight"

instead of the current "edge.width= network". Seems to work and makes a visible 
difference...

HTH,
Kimmo

su, 2024-02-25 kello 19:11 +, Kimmo Elo kirjoitti:
> 
> Hi again,
> 
> your code is still not reproducible without modifications, but I 
> succeed in getting the data straight. All read.csv-command are missing 
> 'sep="\t"', it is need to read you tsv-data.
> 
> And it could be more reproducible if you used e.g.
> 
> --- snip ---
> aes<-read.csv(text="A.A B.B C.C D.D E.E F.F 
> A.A 0   0   5   5   5   5 B.B 4   0   
> 1   1   1   1 C.C 5   5   0   5   4   
> 2 D.D 5   0   5   0   5   3 E.E 5   1   
> 5   5   0   4 F.F 1   2   3   4   5   
> 5", sep="\t", row.names = 1)
> --- snip ---
> 
> This would save us from unnecessary copy-pasting :-)
> 
> However, the error is still the same I mentioned in my first reply,
> i.e.:
> 
> network %>% plot(
> vertex.color=clrs[V(.)$community],
> vertex.size=V(.)$hub_score*5,
> vertex.frame.color=V(.)$color,
> vertex.label.color="white",
> vertex.label.cex=0.5,
> vertex.label.family="Helvetica",
> vertex.label.font=1,
> edge.curved=0.5,
> HERE -->edge.width= network,  <-- HERE
> layout=layout_with_mds(.))
> 
> Try to comment out his line and see what happens. What network data 
> variable should be mapped to edge width?
> 
> Best,
> Kimmo
> 
> su, 2024-02-25 kello 09:59 +0100, sibylle.stoec...@gmx.ch kirjoitti:
> > Dear coummunity
> > 
> > Thanks a lot to David and Kimmo. Yes I see now that I need to 
> > provide the two raw tables. Find here the reproducible example.
> > 
> > Kind regards
> > Sibylle
> > 
> > # R-labraries
> > library(circlize)
> > library(ggplot2)
> > library(igraph)
> > library(tidyverse)
> > library(RColorBrewer)
> > library(stringi)
> > library(scico)
> > library(plotly)
> > library(ggraph)
> > 
> > 
> > # Tables
> > aes<-read.csv("Test_adjac.csv", row.names = 1)
> > details<-read.csv("Test_cat.csv")
> > 
> > # Edge table, reorganisation
> > aes_collapsed<-aes %>%
> >   rownames_to_column(var='Names') %>%
> >   tidyr::gather(target, weight, 1:ncol(aes)+1) %>%
> >   dplyr::filter(weight != 0) %>%
> >   mutate(weight = ifelse(weight == "-1", 0, weight)) # here 0 = 
> > negative values
> > 
> > write.csv(aes_collapsed, "edges_table_Test.csv", row.names = F)
> > edge_list<-read.csv("edges_table_Test.csv")
> > 
> > # Network attributes
> > network <- graph_from_data_frame(aes_collapsed, directed= FALSE,
> >  vertices = details)
> > 
> > 
> > temp<-cluster_optimal(network)
> > temp<-cbind(membership=temp$membership, Names=temp$name) 
> > aes_collapsed <- aes_collapsed %>%
> >   merge(temp, by="Names")
> > 
> > 
> > network <- network %>%
> >   set_edge_attr(name = "type", value = factor(aes_collapsed$Names,
> >  ordered =
> > is.ordered(V(network)$name))) %>%
> >   set_edge_attr(name = "membership", value =
> > aes_collapsed$membership) %>%
> >   set_edge_attr(name = "color",
> >   value = c(viridis::viridis(5))
> >   [match(E(.)$type, c(factor(V(.)$name)))]) %>%
> >   set_vertex_attr(name = "trans_v_net", value = c(transitivity(., 
> > type = "local"))) %>%
> >   set_vertex_attr(name = "hub_score", value =
> > c(hub_score(.)$vector))
> >

Re: [R] igraph_vertex

2024-02-26 Thread SIBYLLE STÖCKLI via R-help
Dear Ivan

Thanks a lot.

I used:
windowsFonts(Helvetica = windowsFont("Helvetica"))
No warning now with Helvetica
Additionally I used "sans", similarly no warning  in the first part.

But still not able to open tiff with both versions:

Using "stress" as default layout
> dev.off()
TIFFOpen: figures/AES_network_bymembership.tiff: Cannot open.
RStudioGD 
2 
Warning message:
In dev.off() :
  unable to open TIFF file 'figures/AES_network_bymembership.tiff'

Kind regards
Sibylle

-Original Message-
From: Ivan Krylov  
Sent: Monday, February 26, 2024 10:15 AM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] igraph_vertex

В Mon, 26 Feb 2024 09:02:56 +0100
SIBYLLE STÖCKLI via R-help  пишет:

> In the following code, which loads the tiff file, I get the following 
> error

This warning is definitely worth investigating, but it shouldn't interrupt your 
code. Does the figure come out wrong after you see this warning?

> In doTryCatch(return(expr), name, parentenv, handler) : Character set 
> family not found in the Windows character set database
> 
> --> I am unsure if mySQL is the right solution. I have no experience
> how to change mySQL. 

I see you've tried to do the right thing and searched for the warning message. 
Unfortunately, the search engines are wrong; this doesn't seem related to MySQL.

A similarly-worded warning message exists in the Windows-related font functions 
inside R:

>> warning(_("font family not found in Windows font database"))

If running a sufficiently new version of R, try Sys.setLanguage('en') before 
reproducing the problem and searching for the exact warning message in double 
quotes. (Reset it back using
Sys.setLanguage(your_language_code) or restart R afterwards.) Translated error 
and warning messages are good for understanding, but they fragment the search 
engine results.

I see that a few messages back you set a font family:

>  vertex.label.family="Helvetica",

R probably doesn't know where to get it in order to render the plot as TIFF. If 
you have a copy of Helvetica installed in your system, try registering it using 
windowsFonts(Helvetica = windowsFont("how the font is named in the system")). 
(See help(windowsFonts) for more
information.) Otherwise you may be limited to R's predefined font families.

It's annoying that "Helvetica" exists for PDF plots and such seemingly without 
a problem, but if you change the output format to TIFF, the set of fonts 
available to you changes too. Unfortunately, there are multiple different font 
rendering engines in play, and their predefined lists of fonts also differ.

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] geom_edge & color

2024-03-20 Thread SIBYLLE STÖCKLI via R-help
Dear community

I am using ggraph to plot a network analysis. See part 2 in the working
example.
Besides different colors for different groups of nodes:
--> geom_node_point(aes(size = V(network)$hub_score*200, color=
as.factor(V(network)$community)))
I additionally want to consider different colors for different edge groups
The grouping is defined in the edge_list$relationship: negative relationship
= red and positive relationship = darkblue. The code is working in the way
that the  groups are separated by two colors. However, the code uses not the
assigned colors. Does anyone have any idea how to adapt the code?
--> geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10),
color=c("darkblue", "red")[as.factor(edge_list$relationship)], alpha=0.5)) +

Kind regards
Sibylle




Working example

library(circlize)
library(ggplot2)
library(igraph)
library(tidyverse)
library(RColorBrewer)
library(stringi)
library(scico)
library(plotly)
library(ggraph)

edges_table_Test.csv

Names   target  weight relationship
B.B A.A 4   pos
C.C A.A 5   pos
D.D A.A 5   neg
E.E A.A 5  neg
F.F A.A 1  pos
C.C B.B 5 pos
E.E B.B 1   pos
F.F B.B 2  pos
A.A C.C 5pos
B.B C.C 1pos
D.D C.C 5 pos
E.E C.C 5 pos
F.F C.C 3 pos
A.A D.D 5neg
B.B D.D 1neg
C.C D.D 5neg
E.E D.D 5neg
F.F D.D 4 neg
A.A E.E 5 neg
B.B E.E 1neg
C.C E.E 4neg
D.D E.E 5neg
F.F E.E 5   pos
A.A F.F 5pos
B.B F.F 1   pos
C.C F.F 2   pos
D.D F.F 3  pos
E.E F.F 4   pos
F.F F.F 5   pos

edge_list<-read.csv("edges_table_Test.csv")

network <- graph_from_data_frame(aes_collapsed, directed= FALSE,
 vertices = details)

temp<-cluster_optimal(network)
temp<-cbind(membership=temp$membership, Names=temp$name) aes_collapsed <-
aes_collapsed %>%
  merge(temp, by="Names")


network <- network %>%
  set_edge_attr(name = "type", value = factor(aes_collapsed$Names,
 ordered =
is.ordered(V(network)$name))) %>%
  set_edge_attr(name = "membership", value = aes_collapsed$membership) %>%
  set_edge_attr(name = "color",
  value = c(viridis::viridis(5))
  [match(E(.)$type, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type =
"local"))) %>%
  set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) %>%
  set_vertex_attr(name = "color",
  value = c(viridis::viridis((5)))
  [match(V(.)$name, c(factor(V(.)$name)))]) %>%
  set_vertex_attr(name= "community", value=cluster_optimal(.)$membership)
clrs<-scico(3, palette = "batlow")

### part 1: network plot
par(bg="black")
network %>% plot(
 vertex.color=clrs[V(.)$community],
 vertex.size=V(.)$hub_score*5,
 vertex.frame.color=V(.)$color,
 vertex.label.color="white",
 vertex.label.cex=0.5,
 vertex.label.family="Helvetica",
 vertex.label.font=1,
 edge.curved=0.5,
 edge.width= network,
 layout=layout_with_mds(.))

### part 2: ggraph
tiff("figures/AES_network_bymembership.tiff", width=1000, height=700,
res=120) network %>%
  ggraph(., layout = "auto")+
geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10),
color=c("darkblue", "red")[as.factor(edge_list$relationship)], alpha=0.5)) +

  geom_node_point(aes(size = V(network)$hub_score*200, color=
as.factor(V(network)$community))) +
  geom_node_text(aes(label =  V(network)$name), size=5, color="white",
repel=T)+
  scale_color_scico_d(palette = "batlow")+
  scale_edge_width(range = c(0.2,4))+
  scale_size(range = c(0.5,20)) +
  #scale_edge_color_manual(values = c(scico(21, palette="batlow")))+
  theme(plot.background = element_rect(fill = "black"),
legend.position = "right",
panel.background = element_rect(fill = "black"))
dev.off()

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] geom_edge & color

2024-03-22 Thread SIBYLLE STÖCKLI via R-help
Dear community

 

Find enclosed the full working example.

 

Many thanks

Sibylle

 

Test_cat.csv


Names

Subcategory_type

sources.cyto

source

Factor


A.A

material

"A"

A

1


B.B

material

"B"

B

1


C.C

regulation

"C"

C

1


D.D

regulation

"D"

D

1


E.E

habitat

"E"

E

1


F.F

cultural

"F"

F

1

 

Test_adjac.csv


A.A

B.B

C.C

D.D

E.E

F.F


A.A

0

0

5

5

5

5


B.B

4

0

1

1

1

1


C.C

5

5

0

5

4

2


D.D

5

0

5

0

5

3


E.E

5

1

5

5

0

4


F.F

1

2

3

4

5

5

 

 

Edges_table-Test.csv

 


Names

target

weight

relationship


B.B

A.A

4

pos


C.C

A.A

5

pos


D.D

A.A

5

neg


E.E

A.A

5

pos


F.F

A.A

1

pos


C.C

B.B

5

pos


E.E

B.B

1

pos


F.F

B.B

2

neg


A.A

C.C

5

pos


B.B

C.C

1

pos


D.D

C.C

5

pos


E.E

C.C

5

pos


F.F

C.C

3

pos


A.A

D.D

5

neg


B.B

D.D

1

pos


C.C

D.D

5

pos


E.E

D.D

5

pos


F.F

D.D

4

pos


A.A

E.E

5

pos


B.B

E.E

1

pos


C.C

E.E

4

pos


D.D

E.E

5

pos


F.F

E.E

5

pos


A.A

F.F

5

pos


B.B

F.F

1

neg


C.C

F.F

2

pos


D.D

F.F

3

pos


E.E

F.F

4

pos


F.F

F.F

5

pos

 

 

 

#upload librairies

library(circlize)

library(ggplot2)

library(igraph)

library(tidyverse)

library(RColorBrewer)

library(stringi)

library(scico)

library(plotly)

library(ggraph)

 

#upload

aes<-read.csv("Test_adjac.csv", row.names = 1)

details<-read.csv("Test_cat.csv")

 

 

# adjacency  table 

aes_collapsed<-aes %>%

  rownames_to_column(var='Names') %>%

  tidyr::gather(target, weight, 1:ncol(aes)+1) %>%

  dplyr::filter(weight != 0) %>%

  mutate(weight = ifelse(weight == "-1", 0, weight)) # here 0 = negative values

 

write.csv(aes_collapsed, "edges_table-Test.csv", row.names = F)

edge_list<-read.csv("edges_table-Test.csv")

 

 

#create network and add some necessary attributes (vertices) for the plot

 

network <- graph_from_data_frame(aes_collapsed, directed= FALSE, 

 vertices = details)

 

### network and vertex with 'subcategory_type'

 

temp<-cluster_optimal(network)

temp<-cbind(membership=temp$membership, Names=temp$name)

aes_collapsed <- aes_collapsed %>%

  merge(temp, by="Names")

 

network <- network %>%

  set_edge_attr(name = "type", value = factor(aes_collapsed$Names, 

 ordered = 
is.ordered(V(network)$name))) %>%

  set_edge_attr(name = "membership", value = aes_collapsed$membership) %>%

  set_edge_attr(name = "color", 

  value = c(viridis::viridis(21))

  [match(E(.)$type, c(factor(V(.)$name)))]) %>%

  set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type = 
"local"))) %>%

  set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) %>%

  set_vertex_attr(name = "color", 

  value = c(viridis::viridis((21)))

  [match(V(.)$name, c(factor(V(.)$name)))]) %>%

  set_vertex_attr(name= "community", value=cluster_optimal(.)$Subcategory_type)

 

clrs<-scico(3, palette = "batlow")

 

windowsFonts(Helvetica = windowsFont("Helvetica")) 

 

par(bg="black")

network %>% plot(

 vertex.color=clrs[V(.)$community], 

 vertex.size=V(.)$hub_score*20, 

 vertex.frame.color=V(.)$color, 

 vertex.label.color="white", 

 vertex.label.cex=0.4, 

 vertex.label.family="Helvetica",

 vertex.label.font=0.75,

 edge.curved=0.5,

 edge.width= E(.)$weight,

 edge.color = ifelse(edge_list$relationship == "pos", "blue", "red"),

 layout=layout_with_mds(.))

 

tiff("figures/Test_network_bysubcatecory.tiff", width=1000, height=900, res=120)

network %>%

  ggraph(., layout = "auto")+

  geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10), 
color=c("darkblue", "red")[as.factor(edge_list$relationship)], alpha=0.5)) + 

  geom_node_point(aes(size = V(network)$hub_score*200, color= 
as.factor(V(network)$community))) +

  geom_node_text(aes(label =  V(network)$name), size=3, color="white", repel=T)+

  scale_color_scico_d(palette = "batlow")+

  scale_edge_width(range = c(0.2,4))+

  scale_size(range = c(0.5,15)) +

  theme(plot.background = element_rect(fill = "black"),

legend.position = "right",

panel.background = element_rect(fill = "black"))

dev.off()

 

-Original Message-
From: R-help  On Behalf Of Kimmo Elo
Sent: Thursday, March 21, 2024 10:51 AM
To: r-help@r-project.org
Subject: Re: [R] geom_edge & color

 

Dear Sibylle,

 

your example is not working! E.g. no

Re: [R] geom_edge & color

2024-03-24 Thread SIBYLLE STÖCKLI via R-help
gt; D.D
> 
> E.E
> 
> 5
> 
> pos
> 
> 
> F.F
> 
> E.E
> 
> 5
> 
> pos
> 
> 
> A.A
> 
> F.F
> 
> 5
> 
> pos
> 
> 
> B.B
> 
> F.F
> 
> 1
> 
> neg
> 
> 
> C.C
> 
> F.F
> 
> 2
> 
> pos
> 
> 
> D.D
> 
> F.F
> 
> 3
> 
> pos
> 
> 
> E.E
> 
> F.F
> 
> 4
> 
> pos
> 
> 
> F.F
> 
> F.F
> 
> 5
> 
> pos
> 
>  
> 
>  
> 
>  
> 
> #upload librairies
> 
> library(circlize)
> 
> library(ggplot2)
> 
> library(igraph)
> 
> library(tidyverse)
> 
> library(RColorBrewer)
> 
> library(stringi)
> 
> library(scico)
> 
> library(plotly)
> 
> library(ggraph)
> 
>  
> 
> #upload
> 
> aes<-read.csv("Test_adjac.csv", row.names = 1)
> 
> details<-read.csv("Test_cat.csv")
> 
>  
> 
>  
> 
> # adjacency  table
> 
> aes_collapsed<-aes %>%
> 
>   rownames_to_column(var='Names') %>%
> 
>   tidyr::gather(target, weight, 1:ncol(aes)+1) %>%
> 
>   dplyr::filter(weight != 0) %>%
> 
>   mutate(weight = ifelse(weight == "-1", 0, weight)) # here 0 = 
> negative values
> 
>  
> 
> write.csv(aes_collapsed, "edges_table-Test.csv", row.names = F)
> 
> edge_list<-read.csv("edges_table-Test.csv")
> 
>  
> 
>  
> 
> #create network and add some necessary attributes (vertices) for the 
> plot
> 
>  
> 
> network <- graph_from_data_frame(aes_collapsed, directed= FALSE,
> 
>  vertices = details)
> 
>  
> 
> ### network and vertex with 'subcategory_type'
> 
>  
> 
> temp<-cluster_optimal(network)
> 
> temp<-cbind(membership=temp$membership, Names=temp$name)
> 
> aes_collapsed <- aes_collapsed %>%
> 
>   merge(temp, by="Names")
> 
>  
> 
> network <- network %>%
> 
>   set_edge_attr(name = "type", value = factor(aes_collapsed$Names,
> 
>  ordered =
> is.ordered(V(network)$name))) %>%
> 
>   set_edge_attr(name = "membership", value = aes_collapsed$membership) 
> %>%
> 
>   set_edge_attr(name = "color",
> 
>   value = c(viridis::viridis(21))
> 
>   [match(E(.)$type, c(factor(V(.)$name)))]) %>%
> 
>   set_vertex_attr(name = "trans_v_net", value = c(transitivity(., type 
> =
> "local"))) %>%
> 
>   set_vertex_attr(name = "hub_score", value = c(hub_score(.)$vector)) 
> %>%
> 
>   set_vertex_attr(name = "color",
> 
>   value = c(viridis::viridis((21)))
> 
>   [match(V(.)$name, c(factor(V(.)$name)))]) %>%
> 
>   set_vertex_attr(name= "community",
> value=cluster_optimal(.)$Subcategory_type)
> 
>  
> 
> clrs<-scico(3, palette = "batlow")
> 
>  
> 
> windowsFonts(Helvetica = windowsFont("Helvetica"))
> 
>  
> 
> par(bg="black")
> 
> network %>% plot(
> 
>  vertex.color=clrs[V(.)$community],
> 
>  vertex.size=V(.)$hub_score*20,
> 
>  vertex.frame.color=V(.)$color,
> 
>  vertex.label.color="white",
> 
>  vertex.label.cex=0.4,
> 
>  vertex.label.family="Helvetica",
> 
>  vertex.label.font=0.75,
> 
>  edge.curved=0.5,
> 
>  edge.width= E(.)$weight,
> 
>  edge.color = ifelse(edge_list$relationship == "pos", "blue", 
> "red"),
> 
>  layout=layout_with_mds(.))
> 
>  
> 
> tiff("figures/Test_network_bysubcatecory.tiff", width=1000, 
> height=900,
> res=120)
> 
> network %>%
> 
>   ggraph(., layout = "auto")+
> 
>   geom_edge_arc(curvature=0.3, aes(width=(E(network)$weight/10), 
> color=c("darkblue", "red")[as.factor(edge_list$relationship)],
> alpha=0.5)) +
> 
>   geom_node_point(aes(size = V(network)$hub_score*200, color=
> as.factor(V(network)$community))) +
> 
>   geom_node_text(aes(label =  V(network)$name), size=3, color="white", 
> repel=T)+
> 
>   scale_color_scico_d(palette = "batlow")+
> 
>   scale_edge_width(range = c(0.2,4))+
> 
>   scale_size(range = c(0.5,15)) +
> 
>   theme(plot.background = element_rect(fill = "black"),
> 
> legend.position = "right",
> 
> panel.background = element_rect(fill = "black"))
> 
> dev.off()
>

[R] Import multiple tif raster

2024-04-18 Thread SIBYLLE STÖCKLI via R-help
Dear community

My aim is to import multiple .tif raster files using the help here:
https://stackoverflow.com/questions/52746936/how-to-efficiently-import-multi
ple-raster-tif-files-into-r

Does anyone now about the error "subscripts out of bounds"?
I am not sure about the check with alllrasters: is list() ok or should there
be a number (the number of imported .tif files?

Kind regards
Sibylle


> library(terra)
> library(raster)
> getwd()
[1] "C:/Users/Sibylle Stöckli/Desktop"
> 
> #first import all files in a single folder as a list 
> rastlist <- list.files(path =
"/NCCS_Impacts_Lot2_2022/InVEST/Species_Input/bee_presence",
pattern='.tif$', all.files= T, full.names= T)
> 
> #import all raster files in folder using lapply
> allrasters <- lapply(rastlist, raster)
> 
> #to check the index numbers of all imported raster list elements
> allrasters
list()
> 
> #call single raster element
> allrasters[[1]]
Error in allrasters[[1]] : subscript out of bounds

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Import multiple tif raster

2024-04-18 Thread SIBYLLE STÖCKLI via R-help
Dear Ivan

Thanks a lot.

I tried now to provide the full path. However probably the "ö" in the path 
produces the error, would that be possible?

> #first import all files in a single folder as a list 
> rastlist <- list.files(path = "C:\Users\Sibylle 
> Stöckli\Desktop\NCCS_Impacts_Lot2_2022\InVEST\Species_Input\valpar_bee_presence",
>  pattern='.tif$', all.files= T, full.names= T)
Error: '\U' used without hex digits in character string (:1:35)

Kind regards
Sibylle

-Original Message-
From: Ivan Krylov  
Sent: Thursday, April 18, 2024 2:39 PM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] Import multiple tif raster

В Thu, 18 Apr 2024 11:08:33 +0200
SIBYLLE STÖCKLI via R-help  пишет:

> > #to check the index numbers of all imported raster list elements 
> > allrasters
> list()
> > 
> > #call single raster element
> > allrasters[[1]]
> Error in allrasters[[1]] : subscript out of bounds

`allrasters` is an empty list, so it doesn't have a first item.
Therefore, allrasters[[1]] is an error. Why is this so? Probably because 
list.files(...) above returned an empty vector.

Check rastlist and/or length(rastlist). Make sure that the path you're giving 
to list.files (the one starting with
/NCCS_Impacts_Lot2_2022/InVEST/...) exists on your computer. Did you mean to 
start it with a slash, making it an absolute path starting from the root of the 
filesystem?

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] Import multiple tif raster

2024-04-18 Thread SIBYLLE STÖCKLI via R-help
Dear community
Dear Ivan

Thanks a lot. The code works now. Solution: direct and full path to the .tif 
files.
I confused back and forward slash


#first import all files in a single folder as a list 
rastlist <- list.files(path = "C:/Users/Sibylle 
Stöckli/Desktop/NCCS_Impacts_Lot2_2022/InVEST/Species_Input/valpar_bee_presence",
 pattern='.tif$', all.files= T, full.names= T)

At the end I got a warning
#to run a function on an individual raster e.g., plot 
> boxplot(allrasters[[1]])
> 
> p<-boxplot(allrasters[[1]])
Warning message:
In .local(x, ...) : taking a sample of 1e+05 cells
> 
Not all of the characters in C:/Users/Sibylle Stöckli/Desktop/Test_Rasterfile.R 
could be encoded using ASCII. To save using a different encoding, choose "File 
| Save with Encoding..." from the main menu.
>

Kind regards
Sibylle

-----Original Message-----
From: R-help  On Behalf Of SIBYLLE STÖCKLI via 
R-help
Sent: Thursday, April 18, 2024 6:48 PM
To: 'Ivan Krylov' ; 'SIBYLLE STÖCKLI via R-help' 

Subject: Re: [R] Import multiple tif raster

Dear Ivan

Thanks a lot.

I tried now to provide the full path. However probably the "ö" in the path 
produces the error, would that be possible?

> #first import all files in a single folder as a list rastlist <- 
> list.files(path = "C:\Users\Sibylle 
> Stöckli\Desktop\NCCS_Impacts_Lot2_2022\InVEST\Species_Input\valpar_bee
> _presence", pattern='.tif$', all.files= T, full.names= T)
Error: '\U' used without hex digits in character string (:1:35)

Kind regards
Sibylle

-Original Message-
From: Ivan Krylov 
Sent: Thursday, April 18, 2024 2:39 PM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] Import multiple tif raster

В Thu, 18 Apr 2024 11:08:33 +0200
SIBYLLE STÖCKLI via R-help  пишет:

> > #to check the index numbers of all imported raster list elements 
> > allrasters
> list()
> > 
> > #call single raster element
> > allrasters[[1]]
> Error in allrasters[[1]] : subscript out of bounds

`allrasters` is an empty list, so it doesn't have a first item.
Therefore, allrasters[[1]] is an error. Why is this so? Probably because 
list.files(...) above returned an empty vector.

Check rastlist and/or length(rastlist). Make sure that the path you're giving 
to list.files (the one starting with
/NCCS_Impacts_Lot2_2022/InVEST/...) exists on your computer. Did you mean to 
start it with a slash, making it an absolute path starting from the root of the 
filesystem?

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] ggplot two-factor legend

2024-07-18 Thread SIBYLLE STÖCKLI via R-help
Hi

I am using ggplot to visualise y for a two-factorial group (Bio: 0 and 1) x
= 6 years. I was able to adapt the colour of the lines (green and red) and
the linetype (solid and dashed).
Challenge: my code produces now two legends. One with the colors for the
group and one with the linetype for the group. Does somebody have a hint how
to adapt the code to produce one legend? Group 0 = red and dashed, Group 1 =
green and solid?


MS1<- MS %>% filter(QI_A!="NA") %>% droplevels()
dev.new(width=4, height=2.75)
par(mar = c(0,6,0,0))
p1<-ggplot(data = MS1, aes(x= Jahr, y= QI_A,group=Bio,color=Bio,
linetype=Bio)) + 
geom_smooth(aes(fill=Bio) , method = "lm" , formula = y ~ x +
I(x^2),linewidth=1) +
theme(panel.background = element_blank())+
theme(axis.line = element_line(colour = "black"))+
  theme(axis.text=element_text(size=18))+
  theme(axis.title=element_text(size=20))+
ylab("Anteil BFF an LN [%]") +xlab("Jahr")+
scale_color_manual(values=c("red","dark green"), labels=c("ÖLN",
"BIO"))+
scale_fill_manual(values=c("red","dark green"), labels= c("ÖLN",
"BIO"))+
theme(legend.title = element_blank())+
  theme(legend.text=element_text(size=20))+
  scale_linetype_manual(values=c("dashed", "solid"))
p1<-p1 + expand_limits(y=c(0, 30))

kind regards
Sibylle

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] ggplot two-factor legend

2024-07-18 Thread SIBYLLE STÖCKLI via R-help
Thanks Jeff

I removed the group parameter in the fp1<-ggplot () line. It doesn't change 
anything.
I suppose I got two legends as in the ggplot () line I have color=Bio & 
linetype=Bio. However, when removing linetype = Bio I just geht red and green. 
For black and white printing I would like the additionally differentiate the 
two lines (groups) in the linetype.

Sibylle

-Original Message-
From: Jeff Newmiller  
Sent: Thursday, July 18, 2024 6:13 PM
To: sibylle.stoec...@gmx.ch; SIBYLLE STÖCKLI via R-help ; 
r-help@r-project.org
Subject: Re: [R] ggplot two-factor legend

If I follow your question, you want redundant aesthetics. Ggplot normally 
notices correlated aesthetic mapping variables and merges the legends, so the 
most likely answer is that your data are not fully correlated in all rows. I 
have also seen this where data are drawn from different dataframes for 
different layers since it is hard to merge factors, but I don't see that here.

You are using the group parameter... try removing that? The group parameter 
overrides the automatic group determination. There might be a syntax for 
specifying correlated grouping, but I don't know it... I normally just verify 
that my data meets the requirements to be automatically identified as 
correlated if that is my goal, since that is a prerequisite anyway.

On July 18, 2024 8:27:05 AM PDT, "SIBYLLE STÖCKLI via R-help" 
 wrote:
>Hi
>
>I am using ggplot to visualise y for a two-factorial group (Bio: 0 and 
>1) x = 6 years. I was able to adapt the colour of the lines (green and 
>red) and the linetype (solid and dashed).
>Challenge: my code produces now two legends. One with the colors for 
>the group and one with the linetype for the group. Does somebody have a 
>hint how to adapt the code to produce one legend? Group 0 = red and 
>dashed, Group 1 = green and solid?
>
>
>MS1<- MS %>% filter(QI_A!="NA") %>% droplevels() dev.new(width=4, 
>height=2.75) par(mar = c(0,6,0,0)) p1<-ggplot(data = MS1, aes(x= Jahr, 
>y= QI_A,group=Bio,color=Bio,
>linetype=Bio)) + 
>   geom_smooth(aes(fill=Bio) , method = "lm" , formula = y ~ x +
>I(x^2),linewidth=1) +
>   theme(panel.background = element_blank())+
>   theme(axis.line = element_line(colour = "black"))+
>  theme(axis.text=element_text(size=18))+
>  theme(axis.title=element_text(size=20))+
>   ylab("Anteil BFF an LN [%]") +xlab("Jahr")+
>   scale_color_manual(values=c("red","dark green"), labels=c("ÖLN", 
>"BIO"))+
>   scale_fill_manual(values=c("red","dark green"), labels= c("ÖLN", 
>"BIO"))+
>   theme(legend.title = element_blank())+
>  theme(legend.text=element_text(size=20))+
>  scale_linetype_manual(values=c("dashed", "solid"))
>p1<-p1 + expand_limits(y=c(0, 30))
>
>kind regards
>Sibylle
>
>__
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide 
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

--
Sent from my phone. Please excuse my brevity.

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] ggplot two-factor legend

2024-07-18 Thread SIBYLLE STÖCKLI via R-help
Thanks a lot Rui and Jeff

Yes including labels=c() in  scale_linetype_manual() was the hint.

Sibylle

-Original Message-
From: Rui Barradas  
Sent: Thursday, July 18, 2024 6:50 PM
To: sibylle.stoec...@gmx.ch; r-help@r-project.org
Subject: Re: [R] ggplot two-factor legend

Às 17:43 de 18/07/2024, Rui Barradas escreveu:
> Às 16:27 de 18/07/2024, SIBYLLE STÖCKLI via R-help escreveu:
>> Hi
>>
>> I am using ggplot to visualise y for a two-factorial group (Bio: 0 
>> and
>> 1) x
>> = 6 years. I was able to adapt the colour of the lines (green and 
>> red) and the linetype (solid and dashed).
>> Challenge: my code produces now two legends. One with the colors for 
>> the group and one with the linetype for the group. Does somebody have 
>> a hint how to adapt the code to produce one legend? Group 0 = red and 
>> dashed, Group 1 = green and solid?
>>
>>
>> MS1<- MS %>% filter(QI_A!="NA") %>% droplevels() dev.new(width=4, 
>> height=2.75) par(mar = c(0,6,0,0)) p1<-ggplot(data = MS1, aes(x= 
>> Jahr, y= QI_A,group=Bio,color=Bio,
>> linetype=Bio)) +
>>  geom_smooth(aes(fill=Bio) , method = "lm" , formula = y ~ x 
>> +
>> I(x^2),linewidth=1) +
>> theme(panel.background = element_blank())+
>> theme(axis.line = element_line(colour = "black"))+
>>theme(axis.text=element_text(size=18))+
>>theme(axis.title=element_text(size=20))+
>> ylab("Anteil BFF an LN [%]") +xlab("Jahr")+
>> scale_color_manual(values=c("red","dark green"), labels=c("ÖLN", 
>> "BIO"))+
>> scale_fill_manual(values=c("red","dark green"), labels= c("ÖLN", 
>> "BIO"))+
>> theme(legend.title = element_blank())+
>>theme(legend.text=element_text(size=20))+
>>scale_linetype_manual(values=c("dashed", "solid"))
>> p1<-p1 + expand_limits(y=c(0, 30))
>>
>> kind regards
>> Sibylle
>>
>> __
>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> Hello,
> 
> To have one legend only, the labels must be the same. Try using
> 
> labels=c("ÖLN", "BIO")
> 
> in
> 
> scale_linetype_manual(values=c("dashed", "solid"), labels=c("ÖLN", 
> "BIO"))
> 
> 
> Hope this helps,
> 
> Rui Barradas
> 
> 
Hello,

Here is a more complete an answer with the built-in data set mtcars.
Note that the group aesthetic is not used. This is because linetype is 
categorical (after mutate) and there's no need to group again by the same 
variable (am).

Remove labels from scale_linetype_manual and there are two legends but with the 
same labels the legends merge.


library(ggplot2)
library(dplyr)

mtcars %>%
   # linetype must be categorical
   mutate(am = factor(am)) %>%
   ggplot(aes(hp, disp, color = am, linetype = am)) +
   geom_line() +
   scale_color_manual(
 values = c("red","dark green"),
 labels = c("ÖLN", "BIO")
   ) +
   scale_linetype_manual(
 values = c("dashed", "solid"),
 labels = c("ÖLN", "BIO")
   ) +
   theme_bw()


Hope this helps,

Rui Barradas



-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença 
de vírus.
www.avg.com

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] geom_smooth with sd

2024-08-11 Thread SIBYLLE STÖCKLI via R-help
Dear community

 

Using after_stat() I was able to visualise ggplot with standard deviations
instead of a confidence interval as seen in the R help.

 

p1<-ggplot(data = MS1, aes(x= Jahr, y= QI_A,color=Bio, linetype=Bio)) + 

geom_smooth(aes(fill=Bio,
ymax=after_stat(y+se*sqrt(length(y))), ymin=after_stat(y-se*sqrt(y))) ,
method = "lm" , formula = y ~ x + I(x^2),linewidth=1) +

theme(panel.background = element_blank())+

theme(axis.line = element_line(colour = "black"))+

  theme(axis.text=element_text(size=18))+

  theme(axis.title=element_text(size=20))+

ylab("Anteil BFF an LN [%]") +xlab("Jahr")+

  scale_color_manual(values=c("red","darkgreen"), labels=c("�LN", "BIO"))+

  scale_fill_manual(values=c("red","darkgreen"), labels= c("�LN", "BIO"))+

theme(legend.title = element_blank())+

  theme(legend.text=element_text(size=20))+

  scale_linetype_manual(values=c("dashed", "solid"), labels=c("�LN", "BIO"))

p1<-p1 + expand_limits(y=c(0, 30))

 

When comparing the plots to the simple statistics the standard deviation do
not match. I assume it is because of the na.rm=TRUE which does not match
length(y) in the  after_stat code. However I was not able to adapt the code
using NA values?

 

Simple statistics

> mean(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 26.81225

> sd(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 21.12419

> mean(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.86196

> sd(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.00405

 

Kind regards

Sibylle


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] geom_smooth with sd

2024-08-11 Thread SIBYLLE STÖCKLI via R-help
Thanks Erin

 

Quite relevant. Yes now +sd and -sd are the same values. However they are about 
+/- 5 and not the values received by the simple code here. I still think it is 
as the length of y differs.

 

Simple statistics

> mean(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 26.81225

> sd(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 21.12419

> mean(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.86196

> sd(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.00405



Kind regards

Sibylle 

 

 

 

From: Erin Hodgess  
Sent: Sunday, August 11, 2024 6:30 PM
To: sibylle.stoec...@gmx.ch
Cc: R-help@r-project.org
Subject: Re: [R] geom_smooth with sd

 

Hi!

 

This is probably completely off base, but your ymin and y max setup lines are 
different.  One uses sqrt(y), while the second uses sqrt(length(y)).

 

Could that play a part, please?

 

Thank you






Erin Hodgess, PhD

mailto: erinm.hodg...@gmail.com <mailto:erinm.hodg...@gmail.com> 

 

 

On Sun, Aug 11, 2024 at 10:10 AM SIBYLLE STÖCKLI via R-help 
mailto:r-help@r-project.org> > wrote:

Dear community



Using after_stat() I was able to visualise ggplot with standard deviations
instead of a confidence interval as seen in the R help.



p1<-ggplot(data = MS1, aes(x= Jahr, y= QI_A,color=Bio, linetype=Bio)) + 

geom_smooth(aes(fill=Bio,
ymax=after_stat(y+se*sqrt(length(y))), ymin=after_stat(y-se*sqrt(y))) ,
method = "lm" , formula = y ~ x + I(x^2),linewidth=1) +

theme(panel.background = element_blank())+

theme(axis.line = element_line(colour = "black"))+

  theme(axis.text=element_text(size=18))+

  theme(axis.title=element_text(size=20))+

ylab("Anteil BFF an LN [%]") +xlab("Jahr")+

  scale_color_manual(values=c("red","darkgreen"), labels=c("ÖLN", "BIO"))+

  scale_fill_manual(values=c("red","darkgreen"), labels= c("ÖLN", "BIO"))+

theme(legend.title = element_blank())+

  theme(legend.text=element_text(size=20))+

  scale_linetype_manual(values=c("dashed", "solid"), labels=c("ÖLN", "BIO"))

p1<-p1 + expand_limits(y=c(0, 30))



When comparing the plots to the simple statistics the standard deviation do
not match. I assume it is because of the na.rm=TRUE which does not match
length(y) in the  after_stat code. However I was not able to adapt the code
using NA values?



Simple statistics

> mean(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 26.81225

> sd(MS2020[MS2020$Bio=="1",]$QI_A, na.rm=TRUE)

[1] 21.12419

> mean(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.86196

> sd(MS2020[MS2020$Bio=="0",]$QI_A, na.rm=TRUE)

[1] 15.00405



Kind regards

Sibylle


[[alternative HTML version deleted]]

__
R-help@r-project.org <mailto:R-help@r-project.org>  mailing list -- To 
UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] geom_boxplot nocht=TRUE

2024-08-15 Thread SIBYLLE STÖCKLI via R-help
Dear community

 

I tried to run my ggplot() +geom_boxplot() code using nocht=TRUE, but probably 
my term noch=TRUE is at the wrong position?

 

Error:

Error in `geom_boxplot()`:

! Problem while converting geom to grob.

ℹ Error occurred in the 1st layer.

Caused by error in `ans[ypos] <- rep(yes, length.out = len)[ypos]`:

! replacement has length zero

Run `rlang::last_trace()` to see where the error occurred.

Warning message:

In rep(yes, length.out = len) : 'x' is NULL so the result will be NULL

> rlang::last_trace()



Error in `geom_boxplot()`:

! Problem while converting geom to grob.

ℹ Error occurred in the 1st layer.

Caused by error in `ans[ypos] <- rep(yes, length.out = len)[ypos]`:

! replacement has length zero

---

Backtrace:

 ▆

  1. ├─base (local) ``(x)

  2. └─ggplot2:::print.ggplot(x)

  3.   ├─ggplot2::ggplot_gtable(data)

  4.   └─ggplot2:::ggplot_gtable.ggplot_built(data)

  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$draw_geom(d, layout)

14.   └─ggplot2 (local) draw_geom(..., self = self)

15. └─self$geom$draw_layer(...)

16.   └─ggplot2 (local) draw_layer(..., self = self)

17. └─base::lapply(...)

18.   └─ggplot2 (local) FUN(X[[i]], ...)

19. ├─rlang::inject(self$draw_panel(data, panel_params, 
coord, !!!params))

20. └─self$draw_panel(...)

21.   └─ggplot2 (local) draw_panel(..., self = self)

22. └─base::lapply(...)

23.   └─ggplot2 (local) FUN(X[[i]], ...)

24. └─self$draw_group(group, panel_params, coord, 
...)

25.   └─ggplot2 (local) draw_group(..., self = self)

26. ├─ggplot2:::data_frame0(...)

27. │ └─vctrs::data_frame(..., .name_repair = 
"minimal")

28. │   └─rlang::list2(...)

29. └─base::ifelse(notch, data$notchlower, NA)

Run rlang::last_trace(drop = FALSE) to see 5 hidden frames.

 

 

 

 

Code:

 

MS1<- MS %>% filter(QI_A!="NA") %>% droplevels()

MS1$Jahr<-as.factor(MS1$Jahr)

 

MS1s <- MS1 %>%

  group_by(MS1$Jahr, MS1$Bio) %>%

  summarise(

y0 = quantile(QI_A, 0.05),

y25 = quantile(QI_A, 0.25),

y50 = mean(QI_A),

y75 = quantile(QI_A, 0.75),

y100 = quantile(QI_A, 0.95))

 

MS1s

colnames(MS1s)[1]<-"Jahr"

colnames(MS1s)[2]<-"Bio"

MS1s

 

p1<-ggplot(MS1s, aes(Jahr,  fill = as.factor(Bio))) +

  geom_boxplot(

aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),

stat = "identity", notch=TRUE

  ) +

  theme(panel.background = element_blank())+

  theme(axis.line = element_line(colour = "black"))+

  theme(axis.text=element_text(size=18))+

  theme(axis.title=element_text(size=20))+

  ylab("Anteil BFF an LN [%]") +xlab("Jahr")+

  scale_color_manual(values=c("red","darkgreen"), labels=c("ÖLN", "BIO"))+

  scale_fill_manual(values=c("red","darkgreen"), labels= c("ÖLN", "BIO"))+

  theme(legend.title = element_blank())+

  theme(legend.text=element_text(size=20))

p1<-p1 + expand_limits(y=c(0, 80))

p1

 


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] allequal diff

2024-08-15 Thread SIBYLLE STÖCKLI via R-help
Dear community



Similar to the example of the rdocumentation, my idea is to use all.equal
and to print the difference.

https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/all.equal



> d45 <- pi*(1/4 + 1:10)

> stopifnot(

+ all.equal(tan(d45), rep(1, 10)))  # TRUE, but

> all  (tan(d45) == rep(1, 10)) # FALSE, since not exactly

[1] FALSE

> all.equal(tan(d45), rep(1, 10), tolerance = 0)  # to see difference

[1] "Mean relative difference: 1.29526e-15"

>



Unfortunately, I just get "FALSE" not the difference.

> r2_resampled <- resample(r2, r1)

> compareRaster(r1, r2_resampled)

[1] TRUE

> # Compare rasters

> result <- all.equal(r1, r2_resampled)

Warning message:

In compareRaster(target, current, ..., values = values, stopiffalse =
stopiffalse,  :

  not all objects have the same values

> print(result)

[1] FALSE

>



Kind regards

Sibylle


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] allequal diff

2024-08-15 Thread SIBYLLE STÖCKLI via R-help
Dear Ben

 

Many thanks.

I see that a second challenge are NA values. Is it possible to consider 
na.rm=TRUE?

 

> r2_resampled <- resample(r2, r1)

> compareRaster(r1, r2_resampled)

[1] TRUE

> 

> all.equal(getValues(r1), getValues(r2_resampled), tolerance = 0)

[1] "'is.NA' value mismatch: 9544032 in current 66532795 in target"

 

Kind regards

Sibylle 

 

 

-Original Message-
From: R-help  On Behalf Of Ben Bolker
Sent: Friday, August 16, 2024 1:06 AM
To: r-help@r-project.org
Subject: Re: [R] allequal diff

 

 

   Digging into the code for raster::compareRaster():

 

library(raster)

r <- raster(ncol=3, nrow=3)

values(r) <- 1:ncell(r)

r2 <- r

values(r2) <- c(1:8,10)

all.equal(getValues(r), getValues(r2), tolerance = 0) [1] "Mean relative 
difference: 0.111"

 

compareRaster has fancier machinery internally for doing the comparison for 
large rasters a block at a time if everything can't fit in memory at the same 
time ...

 

 

 

 

On 2024-08-15 9:14 a.m., SIBYLLE STÖCKLI via R-help wrote:

> Dear community

> 

> 

> 

> Similar to the example of the rdocumentation, my idea is to use 

> all.equal and to print the difference.

> 

>  <https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/all> 
> https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/all

> .equal

> 

> 

> 

>> d45 <- pi*(1/4 + 1:10)

> 

>> stopifnot(

> 

> + all.equal(tan(d45), rep(1, 10)))  # TRUE, but

> 

>> all  (tan(d45) == rep(1, 10)) # FALSE, since not exactly

> 

> [1] FALSE

> 

>> all.equal(tan(d45), rep(1, 10), tolerance = 0)  # to see difference

> 

> [1] "Mean relative difference: 1.29526e-15"

> 

>> 

> 

> 

> 

> Unfortunately, I just get "FALSE" not the difference.

> 

>> r2_resampled <- resample(r2, r1)

> 

>> compareRaster(r1, r2_resampled)

> 

> [1] TRUE

> 

>> # Compare rasters

> 

>> result <- all.equal(r1, r2_resampled)

> 

> Warning message:

> 

> In compareRaster(target, current, ..., values = values, stopiffalse = 

> stopiffalse,  :

> 

>not all objects have the same values

> 

>> print(result)

> 

> [1] FALSE

> 

>> 

> 

> 

> 

> Kind regards

> 

> Sibylle

> 

> 

> [[alternative HTML version deleted]]

> 

> __

>  <mailto:R-help@r-project.org> R-help@r-project.org mailing list -- To 
> UNSUBSCRIBE and more, see 

>  <https://stat.ethz.ch/mailman/listinfo/r-help> 
> https://stat.ethz.ch/mailman/listinfo/r-help

> PLEASE do read the posting guide 

>  <http://www.R-project.org/posting-guide.html> 
> http://www.R-project.org/posting-guide.html

> and provide commented, minimal, self-contained, reproducible code.

 

--

Dr. Benjamin Bolker

Professor, Mathematics & Statistics and Biology, McMaster University Director, 
School of Computational Science and Engineering  > E-mail is sent at my 
convenience; I don't expect replies outside of working hours.

 

__

 <mailto:R-help@r-project.org> R-help@r-project.org mailing list -- To 
UNSUBSCRIBE and more, see  <https://stat.ethz.ch/mailman/listinfo/r-help> 
https://stat.ethz.ch/mailman/listinfo/r-help

PLEASE do read the posting guide  <http://www.R-project.org/posting-guide.html> 
http://www.R-project.org/posting-guide.html

and provide commented, minimal, self-contained, reproducible code.


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] allequal diff

2024-08-16 Thread SIBYLLE STÖCKLI via R-help
Many thanks Ivan


Use is.na() on getValues() outputs, combine the two masks using the | operator 
to get a mask of values that are missing in either raster, then negate the mask 
to choose the non-missing values:

all.equal(getValues(r1)[!mask], getValues(r2)[!mask])

--> what do you mean by use is.na() in getValues(). So I need to call getValues 
a second time? I suppose you mean to first prepare a mask using is.na without 
getValues and then in the second step your code?

Kind regards
Sibylle

-Original Message-
From: Ivan Krylov  
Sent: Friday, August 16, 2024 9:28 AM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] allequal diff

В Fri, 16 Aug 2024 07:19:38 +0200
SIBYLLE STÖCKLI via R-help  пишет:

> Is it possible to consider na.rm=TRUE?

> > all.equal(getValues(r1), getValues(r2_resampled), tolerance = 0)
> 
> [1] "'is.NA' value mismatch: 9544032 in current 66532795 in target"

Use is.na() on getValues() outputs, combine the two masks using the | operator 
to get a mask of values that are missing in either raster, then negate the mask 
to choose the non-missing values:

all.equal(getValues(r1)[!mask], getValues(r2)[!mask])

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] allequal diff

2024-08-16 Thread SIBYLLE STÖCKLI via R-help
Here my idea including the error:

 

> m1=r1[r1="NA",]

> m2=r2_resampled[r2_resampled="NA",]

> 

> 

> all.equal(getValues(r1)[!m1], getValues(r2_resampled)[!m2])

[1] "Numeric: lengths (80706867, 65806339) differ"

 

-Original Message-----
From: R-help  On Behalf Of SIBYLLE STÖCKLI via 
R-help
Sent: Friday, August 16, 2024 10:36 AM
To: 'Ivan Krylov' ; 'SIBYLLE STÖCKLI via R-help' 

Subject: Re: [R] allequal diff

 

Many thanks Ivan

 

 

Use is.na() on getValues() outputs, combine the two masks using the | operator 
to get a mask of values that are missing in either raster, then negate the mask 
to choose the non-missing values:

 

all.equal(getValues(r1)[!mask], getValues(r2)[!mask])

 

--> what do you mean by use is.na() in getValues(). So I need to call getValues 
a second time? I suppose you mean to first prepare a mask using is.na without 
getValues and then in the second step your code?

 

Kind regards

Sibylle

 

-Original Message-

From: Ivan Krylov < <mailto:ikry...@disroot.org> ikry...@disroot.org>

Sent: Friday, August 16, 2024 9:28 AM

To: SIBYLLE STÖCKLI via R-help < <mailto:r-help@r-project.org> 
r-help@r-project.org>

Cc:  <mailto:sibylle.stoec...@gmx.ch> sibylle.stoec...@gmx.ch

Subject: Re: [R] allequal diff

 

В Fri, 16 Aug 2024 07:19:38 +0200

SIBYLLE STÖCKLI via R-help < <mailto:r-help@r-project.org> 
r-help@r-project.org> пишет:

 

> Is it possible to consider na.rm=TRUE?

 

> > all.equal(getValues(r1), getValues(r2_resampled), tolerance = 0)

> 

> [1] "'is.NA' value mismatch: 9544032 in current 66532795 in target"

 

Use is.na() on getValues() outputs, combine the two masks using the | operator 
to get a mask of values that are missing in either raster, then negate the mask 
to choose the non-missing values:

 

all.equal(getValues(r1)[!mask], getValues(r2)[!mask])

 

--

Best regards,

Ivan

 

__

 <mailto:R-help@r-project.org> R-help@r-project.org mailing list -- To 
UNSUBSCRIBE and more, see  <https://stat.ethz.ch/mailman/listinfo/r-help> 
https://stat.ethz.ch/mailman/listinfo/r-help

PLEASE do read the posting guide  <http://www.R-project.org/posting-guide.html> 
http://www.R-project.org/posting-guide.html

and provide commented, minimal, self-contained, reproducible code.


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] allequal diff

2024-08-16 Thread SIBYLLE STÖCKLI via R-help
Cool thanks

# values and mask r1
r1 <- getValues(r1)
mask1 <- is.na(r1)
# Do the same for r2
r2 <- getValues(r2_resampled)
mask2 <- is.na(r2)

# Combine the masks
all.equal(r1[!(mask1 & mask2)], r2[!(mask1 & mask2)])


output
> all.equal(r1[!(mask1 & mask2)], r2[!(mask1 & mask2)])
[1] "'is.NA' value mismatch: 389 in current 56989152 in target"

--> so there is just a mismatch in NA not in the xy pixels, right?

Sibylle 



-Original Message-
From: Ivan Krylov  
Sent: Friday, August 16, 2024 10:51 AM
To: sibylle.stoec...@gmx.ch
Cc: 'SIBYLLE STÖCKLI via R-help' 
Subject: Re: [R] allequal diff

В Fri, 16 Aug 2024 10:35:35 +0200
 пишет:

> what do you mean by use is.na() in getValues(). So I need to call 
> getValues a second time?

Not necessarily, but it's one of the options. I was thinking along the lines of:

values1 <- getValues(r1)
mask1 <- is.na(values1)
# Do the same for r2
# Combine the masks
all.equal(values1[!combined_mask], values2[!combined_mask])

Unlike compareRaster(), this assumes that the coordinate grid of r1 and
r2 is already the same and that only some of the values may differ.

> I suppose you mean to first prepare a mask using is.na without 
> getValues and then in the second step your code?

'raster' documentation says that is.na() works on raster objects, so it should 
work.

Even if it didn't work, since you already access the underlying data using 
getValues() and then compare the resulting vectors using all.equal(), using 
is.na(getValues(...)) should definitely work.

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] boxplot notch

2024-08-16 Thread SIBYLLE STÖCKLI via R-help
Dear community

 

I tried the following code using geom_boxplot() and notch=TRUE. Does anyone
know if the command �notch=TRUE� is at the wrong place in my special code
construct?

 

Without notch=TRUE the code provides the planned ggplot.

 

Kind regards

Sibylle

 

Code:

 

MS1<- MS %>% filter(QI_A!="NA") %>% droplevels()

MS1$Jahr<-as.factor(MS1$Jahr)

 

MS1s <- MS1 %>%

  group_by(MS1$Jahr, MS1$Bio) %>%

  summarise(

y0 = quantile(QI_A, 0.05),

y25 = quantile(QI_A, 0.25),

y50 = mean(QI_A),

y75 = quantile(QI_A, 0.75),

y100 = quantile(QI_A, 0.95))

 

MS1s

colnames(MS1s)[1]<-"Jahr"

colnames(MS1s)[2]<-"Bio"

MS1s

 

p1<-ggplot(MS1s, aes(Jahr,  fill = as.factor(Bio))) +

  geom_boxplot(

aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),

stat = "identity", notch=TRUE

  ) +

  theme(panel.background = element_blank())+

  theme(axis.line = element_line(colour = "black"))+

  theme(axis.text=element_text(size=18))+

  theme(axis.title=element_text(size=20))+

  ylab("Anteil BFF an LN [%]") +xlab("Jahr")+

  scale_color_manual(values=c("red","darkgreen"), labels=c("�LN", "BIO"))+

  scale_fill_manual(values=c("red","darkgreen"), labels= c("�LN", "BIO"))+

  theme(legend.title = element_blank())+

  theme(legend.text=element_text(size=20))

p1<-p1 + expand_limits(y=c(0, 80))

p1


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] boxplot notch

2024-08-16 Thread SIBYLLE STÖCKLI via R-help
Thanks Ben,

Here the reproducible example.
It works without notch=TRUE, but provides an error with notch=TURE

Error in `geom_boxplot()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 1st layer.
Caused by error in `ans[ypos] <- rep(yes, length.out = len)[ypos]`:
! replacement has length zero
Run `rlang::last_trace()` to see where the error occurred.
Warning message:
In rep(yes, length.out = len) : 'x' is NULL so the result will be NULL


Data
Farm_ID JahrBio QI_A
1   20151   9.5
2   20181   15.7
3   20201   21.5
1   20151   50.5
2   20181   12.9
3   20201   11.2
1   20151   30.6
2   20181   28.7
3   20201   29.8
1   20151   30.1
2   20181   NA
3   20201   16.9
1   20150   6.5
2   20180   7.9
3   20200   10.2
1   20150   11.2
2   20180   18.5
3   20200   29.5
1   20150   25.1
2   20180   16.1
3   20200   15.9
1   20150   10.1
2   20180   8.4
3   20200   3.5
1   20150   NA
2   20180   NA
3   20200   3.5


Code
setwd("C:/Users/Sibylle Stöckli/Desktop/")
#.libPaths()
getwd()  

#libraries laden
library("ggplot2")
library("gridExtra")  
library(scales)
library(nlme)
library(arm)
library(blmeco)
library(stats)  
library(dplyr)
library(ggpubr)
library(patchwork)
library(plotrix)
library(tidyverse)
library(dplyr)

#read data
MS = read.delim("Test1.txt", na.strings="NA")
names(MS)

MS$Jahr<-as.numeric(MS$Jahr)
MS$Bio<-as.factor(MS$Bio)
str(MS)

# boxplot BFF QI

MS1<- MS %>% filter(QI_A!="NA") %>% droplevels()
MS1$Jahr<-as.factor(MS1$Jahr)

MS1s <- MS1 %>%
  group_by(MS1$Jahr, MS1$Bio) %>%
  summarise(
y0 = quantile(QI_A, 0.05),
y25 = quantile(QI_A, 0.25),
y50 = mean(QI_A),
y75 = quantile(QI_A, 0.75),
y100 = quantile(QI_A, 0.95))

MS1s
colnames(MS1s)[1]<-"Jahr"
colnames(MS1s)[2]<-"Bio"
MS1s

p1<-ggplot(MS1s, aes(Jahr,  fill = as.factor(Bio))) +
  geom_boxplot(
aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = y100),
stat = "identity", notch=TRUE
  ) +
  theme(panel.background = element_blank())+
  theme(axis.line = element_line(colour = "black"))+
  theme(axis.text=element_text(size=18))+
  theme(axis.title=element_text(size=20))+
  ylab("Anteil BFF an LN [%]") +xlab("Jahr")+
  scale_color_manual(values=c("red","darkgreen"), labels=c("ÖLN", "BIO"))+
  scale_fill_manual(values=c("red","darkgreen"), labels= c("ÖLN", "BIO"))+
  theme(legend.title = element_blank())+
  theme(legend.text=element_text(size=20))
p1<-p1 + expand_limits(y=c(0, 80))
p1

-Original Message-
From: R-help  On Behalf Of Ben Bolker
Sent: Friday, August 16, 2024 3:30 PM
To: r-help@r-project.org
Subject: Re: [R] boxplot notch

   I don't see anything obviously wrong here. There may be something subtle, 
but we probably won't be able to help without a reproducible example ...

On 2024-08-16 9:24 a.m., SIBYLLE STÖCKLI via R-help wrote:
> Dear community
> 
>   
> 
> I tried the following code using geom_boxplot() and notch=TRUE. Does 
> anyone know if the command  notch=TRUE  is at the wrong place in my 
> special code construct?
> 
>   
> 
> Without notch=TRUE the code provides the planned ggplot.
> 
>   
> 
> Kind regards
> 
> Sibylle
> 
>   
> 
> Code:
> 
>   
> 
> MS1<- MS %>% filter(QI_A!="NA") %>% droplevels()
> 
> MS1$Jahr<-as.factor(MS1$Jahr)
> 
>   
> 
> MS1s <- MS1 %>%
> 
>group_by(MS1$Jahr, MS1$Bio) %>%
> 
>summarise(
> 
>  y0 = quantile(QI_A, 0.05),
> 
>  y25 = quantile(QI_A, 0.25),
> 
>  y50 = mean(QI_A),
> 
>  y75 = quantile(QI_A, 0.75),
> 
>  y100 = quantile(QI_A, 0.95))
> 
>   
> 
> MS1s
> 
> colnames(MS1s)[1]<-"Jahr"
> 
> colnames(MS1s)[2]<-"Bio"
> 
> MS1s
> 
>   
> 
> p1<-ggplot(MS1s, aes(Jahr,  fill = as.factor(Bio))) +
> 
>geom_boxplot(
> 
>  aes(ymin = y0, lower = y25, middle = y50, upper = y75, ymax = 
> y100),
> 
>  stat = "identity", notch=TRUE
> 
>) +
> 
>theme(panel.background = element_blank())+
> 
>theme(axis.line = element_line(colour = "black"))+
> 
>theme(axis.text=element_text(size=18))+
> 
>theme(axis.title=element_text(size=20))+
> 
>ylab("Anteil BFF an LN [%]") +xlab("J

Re: [R] allequal diff

2024-08-18 Thread SIBYLLE STÖCKLI via R-help
Dear Ivan 

Thanks a lot for this very nice example.

Is it true that all.equal just compares y values?
Based on this help here I think so and the value I got is the difference for 
the y-values.
https://www.statology.org/all-equal-function-r/

However, here I see x and y testing?
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/all.equal
I am actually interested in the x values (x-y coordinates). Test if x-y 
coordinates of both 25-m-pixel rasters are the same. Ther may be a small shift 
or differences in the number of decimal places.

Kind regards
Sibylle



-Original Message-
From: Ivan Krylov  
Sent: Friday, August 16, 2024 11:45 AM
To: sibylle.stoec...@gmx.ch
Cc: 'SIBYLLE STÖCKLI via R-help' 
Subject: Re: [R] allequal diff

В Fri, 16 Aug 2024 11:32:58 +0200
 пишет:

> # values and mask r1
> r1 <- getValues(r1)
> mask1 <- is.na(r1)
> # Do the same for r2
> r2 <- getValues(r2_resampled)
> mask2 <- is.na(r2)
> 
> # Combine the masks
> all.equal(r1[!(mask1 & mask2)], r2[!(mask1 & mask2)])

Let's consider a more tangible example:

# The vectors `x` and `y` start out equal x <- y <- 1:10 # But then their 
different elements are made missing x[c(1,3,4)] <- NA y[c(3,8)] <- NA

Now, `is.na(x) & is.na(y)` gives the third element as the only element missing 
in both x and y:

mask1 <- is.na(x)
mask2 <- is.na(y)
all.equal( # not the comparison you are looking for
 x[!(mask1 & mask2)], # still two more elements missing
 y[!(mask1 & mask2)]  # still one more element missing
)

If you want to ignore all missing elements, you should combine the masks using 
the element-wise "or" operation ("missing in x and/or y"), not the element-wise 
"and" operation ("missing in both x and y at the same time"):

mask1 & mask2 # drops element 3
# [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
mask1 | mask2 # drops elements 1, 3, 4, 8 # [1]  TRUE FALSE  TRUE  TRUE FALSE 
FALSE FALSE  TRUE FALSE FALSE

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] allequal diff

2024-08-19 Thread SIBYLLE STÖCKLI via R-help
Dear Ben and Bert

Thanks very much for the interesting discussion

Yes that why I was additionally using compareRaster(r1,r2) and then resample 
(r2, r1) to adapt the extend.

library(raster)
r1 <- raster("")
r2 <- raster("f")
compareRaster(r1, r2)

extent(r1)
extent(r2)

r2_resampled <- resample(r2, r1)
compareRaster(r1, r2_resampled)

CompareRaster:
Evaluate whether a two or more Raster* objects have the same extent, number of 
rows and columns, projection, resolution, and origin (or a subset of these 
comparisons).

Kind regards
Sibylle

-Original Message-
From: R-help  On Behalf Of Bert Gunter
Sent: Sunday, August 18, 2024 11:21 PM
To: Ben Bolker 
Cc: r-help@r-project.org
Subject: Re: [R] allequal diff

Ah...I see.

Perhaps, then, the maintainer should be contacted, as the desired functionality 
seems similar to that provided in other all.equal methods. I realize that this 
may often not elicit a (prompt) response.

-- Bert


On Sun, Aug 18, 2024 at 11:50 AM Ben Bolker  wrote:
>
> The OP's original problem is that the all.equal method for raster 
> objects (raster:::all.equal.raster), which is a wrapper around the
> compareRaster() function, compares a bunch of different properties of 
> rasters (extent, resolution, values, etc.) and only returns a single 
> overall logical (TRUE/FALSE) value. OP wanted to see the magnitude of 
> the difference (as you could get for more typical all.equal methods by 
> using tolerance=0), but in order to do that one has to dig into the 
> code of compareRaster() and pull out code to make the particular 
> comparisons one wants by applying all.equal to specific components of 
> the raster (it would be nice if there were a built-in way to get this 
> information, but I don't know of one)
>
> On 8/18/24 14:40, Bert Gunter wrote:
> > "Is it true that all.equal just compares y values?"
> >
> > The following may be a bit more than you may have wanted, but I hope 
> > it is nevertheless useful.
> >
> > The first place you should go to for questions like this is the Help 
> > system, not here, i.e.
> > ?all.equal
> >
> > When you do this, you will find that all.equal() is a so-called S3 
> > generic function, which, among other things, means that it works 
> > differently (i.e. "dispatches") depending on its (usually) first 
> > argument. So, for example, if the first argument is of (S3) class 
> > "numeric", it will call the default method, all.equal.default(); if 
> > it's a function, it will call all.equal.function().  Help for 
> > all.equal's basic methods is found in the single all.equal (base) 
> > Help page. However, for non-base R packages, there may be other 
> > different methods provided for classed objects, e.g. perhaps of class 
> > "raster"
> > that would be found by ?all.equal.raster . Or maybe not, if the 
> > class "inherits" from another class, such as "matrix" (Warning: I am 
> > completely unfamiliar with the raster package, so these specifics 
> > are very likely wrong).
> >
> > To sort this sort of thing out, It would probably be useful for you 
> > to find a tutorial on R's S3 class  system (which is really a form 
> > of multiple dispatch) and spend some time with it. There are many 
> > good ones out there. This S3 system is widely used within R and many 
> > packages, so doing this sort of homework now should serve you well 
> > in your future R journey.
> >
> > All IMO obviously.
> >
> > Cheers,
> > Bert
> >
> >
> > On Sun, Aug 18, 2024 at 11:00 AM SIBYLLE STÖCKLI via R-help 
> >  wrote:
> >> Dear Ivan
> >>
> >> Thanks a lot for this very nice example.
> >>
> >> Is it true that all.equal just compares y values?
> >> Based on this help here I think so and the value I got is the difference 
> >> for the y-values.
> >> https://www.statology.org/all-equal-function-r/
> >>
> >> However, here I see x and y testing?
> >> https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/
> >> all.equal I am actually interested in the x values (x-y 
> >> coordinates). Test if x-y coordinates of both 25-m-pixel rasters are the 
> >> same. Ther may be a small shift or differences in the number of decimal 
> >> places.
> >>
> >> Kind regards
> >> Sibylle
> >>
> >>
> >>
> >> -Original Message-
> >> From: Ivan Krylov 
> >> Sent: Friday, August 16, 2024 11:45 AM
> >> To: sibylle.stoec...@gmx.ch
> >> Cc: 'SIBYLLE STÖCKLI via

[R] paired raster boxplots

2024-08-21 Thread SIBYLLE STÖCKLI via R-help
Dear community



I have two raster files (here r and r2: y-axis) and an equal x-axis (here s,
4 classes).

Instead of plotting two boxplots I would like to plot paired boxplots: for
each class the boxplots from r and r2 paired).

I tried to adapt the code, but I am struggling around with the error:



> names(rs) <- c('r', 's', 'r2')

Error in `names<-`(`*tmp*`, value = c("r", "s", "r2")) :

  incorrect number of layer names



Additionally I am not sure how to adapt the function boxplot() with two
rasters, r and r2 and not only r.



Kind regards

Sibylle



Working example:



library(raster)

r <- raster(nc=10, nr=5)

r[] <- runif(ncell(r), min=10, max=20) * 2



r2 <- raster(nc=10, nr=5)

r2[] <- runif(ncell(r2), min=10, max=20) * 2



s <- setValues(r, sample(c(1:4), replace = T, size=50))



rr2s <- stack(r, r2,s)

names(rs) <- c('r', 's', 'r2')



d <- as.data.frame(rr2s)

boxplot(r~s, data= d)




[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] paired raster boxplots

2024-08-23 Thread SIBYLLE STÖCKLI via R-help
Dear Ivan

Many thanks.

Using my own dataset, my "s" is a layer shape file.
Somewhere I need to define : snew<-s$Unterregio

I tried it to do it before stack(), but it seems to be the wrong way. Do you 
have any suggestion?

Code:

> #first import all files in a single folder as a list 
> rastlist_pres <- list.files(path ="C:/Users/._bee_presence", 
> pattern='.tif$', all.files= T, full.names= T)
> rastlist_RCP85P2 <- list.files(path ="C:/Users/_bee_RCP85P2", 
> pattern='.tif$', all.files= T, full.names= T)
> 
> 
> #import all raster files in folder using lapply 
> allrasters_pres <- lapply(rastlist_pres, raster)
> allrasters_RCP85P2 <- lapply(rastlist_RCP85P2, raster)

> sf <- read_sf("C:/Users/._BiogeoRegion.shp")
> names(sf)

> names(sf)
 [1] "RegionNumm" "RegionName" "Unterregio" "Unterreg_1" "ObjNummer"  "Version" 
   "Shape_Leng" "Shape_Area" "DERegionNa" "FRRegionNa" "ITRegionNa" 
"DEBioBedeu" "FRBioBedeu" "ITBioBedeu"
[15] "geometry"

> s<-sf$Unterregio
> r<-allrasters_pres[[1]]
> 
> 
> rs <- stack(r, s)
> names(rs) <- c('r', 's')
Error in `names<-`(`*tmp*`, value = c("r", "s")) : 
  incorrect number of layer names


-Original Message-
From: Ivan Krylov  
Sent: Thursday, August 22, 2024 4:50 PM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] paired raster boxplots

В Thu, 22 Aug 2024 08:46:03 +0200
SIBYLLE STÖCKLI via R-help  пишет:

> rr2s <- stack(r, r2,s)

> > names(rs) <- c('r', 's', 'r2')
> 
> Error in `names<-`(`*tmp*`, value = c("r", "s", "r2")) :
> 
>   incorrect number of layer names

The error must be happening because the variable named 'rs' in your workspace 
originates from some other code you have previously run. The code "works" if 
you replace names(rs) by names(rr2s), but the plot isn't very useful because 
d$s are real numbers in this example and they don't form groups for d$r.

Are you interested in a boxplot where the boxes are grouped by two, one for 'r' 
and one for 'r2'? I'm sure they are not impossible to produce manually using 
the boxplot function, but the 'lattice' or 'ggplot2'
packages would make them much easier. You will need to reshape your data into 
long format, with the "value" column for the r/r2 value, the "kind" column 
saying "r" or "r2", and the "s" column:
https://stackoverflow.com/q/20172560

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] paired raster boxplots

2024-08-24 Thread SIBYLLE STÖCKLI via R-help
Dear Ivan
Dear community

Quite nice book recommendation.
Yes indeed my raster "s" (the shape file for the boxplot classes) has several 
layers. That's way I tried to select a layer by " s<-sf$Unterregio".

> sf <- read_sf("C:/Users/._BiogeoRegion.shp")
> names(sf)

> names(sf)
 [1] "RegionNumm" "RegionName" "Unterregio" "Unterreg_1" "ObjNummer"  "Version" 
   "Shape_Leng" "Shape_Area" "DERegionNa" "FRRegionNa" "ITRegionNa" 
"DEBioBedeu" "FRBioBedeu" "ITBioBedeu"
[15] "geometry"

> s<-sf$Unterregio
> r<-allrasters_pres[[1]]

Kind regards
Sibylle

-Original Message-
From: Ivan Krylov  
Sent: Friday, August 23, 2024 5:30 PM
To: sibylle.stoec...@gmx.ch
Cc: 'SIBYLLE STÖCKLI via R-help' 
Subject: Re: [R] paired raster boxplots

В Fri, 23 Aug 2024 10:15:55 +0200
 пишет:

> > s<-sf$Unterregio
> > r<-allrasters_pres[[1]]
> > 
> > 
> > rs <- stack(r, s)
> > names(rs) <- c('r', 's')
> Error in `names<-`(`*tmp*`, value = c("r", "s")) : 
>   incorrect number of layer names

It looks like at least one of the rasters 'r' and 's' has multiple layers. What 
does names(rs) return? I would offer more detailed advice, but I don't know 
'raster' that well.

The "R Inferno" book [1] offers a lot of generic-R troubleshooting advice, 
which should help you progress past errors like this one without waiting for 
someone on R-help to reply.

--
Best regards,
Ivan

[1] https://www.burns-stat.com/documents/books/the-r-inferno/

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] paired raster boxplots

2024-08-25 Thread SIBYLLE STÖCKLI via R-help
I see, the selection of the layers in shape or raster file is tricky.

Here what I found out:
- It seems that my raster file r is fine, but it is definitively my shape file 
s that causes problems reading the right layer: read_sf should be ok, because 
it reads in all layers, names(sf). However, when selecting the third layer it 
reads in number 3 (Unterregio) and number 15 (geometry). Secondly when using 
stack() it does not read in the s layer (probably because there are two layers).

> 
> sf <- read_sf("C:/Users/Sibylle 
> Stöckli/Desktop/NCCS_Impacts_Lot2_2022/InVEST/BAFU_ALLEMA_strata/Grossraume/data/BiogeographischeRegionen/N2020_Revision_BiogeoRegion.shp")
> names(sf)
 [1] "RegionNumm" "RegionName" "Unterregio" "Unterreg_1" "ObjNummer"  "Version" 
   "Shape_Leng" "Shape_Area" "DERegionNa" "FRRegionNa" "ITRegionNa" 
"DEBioBedeu" "FRBioBedeu" "ITBioBedeu"
[15] "geometry"  
> 
> s<-sf[3]
> names(s)
[1] "Unterregio" "geometry"  
>

> r<-allrasters_pres[[1]]
> names(r)
[1] "Andrena.barbilabris_glo_ensemble"
> 
> 
> rs <- stack(r, s)
> names(rs) <- c('r', 's')
Error in `names<-`(`*tmp*`, value = c("r", "s")) : 
  incorrect number of layer names
> names(rs)
[1] "Andrena.barbilabris_glo_ensemble"
> 
>



-Original Message-
From: Ivan Krylov  
Sent: Saturday, August 24, 2024 6:04 PM
To: sibylle.stoec...@gmx.ch
Cc: 'SIBYLLE STÖCKLI via R-help' 
Subject: Re: [R] paired raster boxplots

В Sat, 24 Aug 2024 10:24:36 +0200
 пишет:

> Yes indeed my raster "s" (the shape file for the boxplot classes) has 
> several layers.

If 's' contains more than one layer, then this already prevents you from giving 
two names to stack(r, s).

> That's way I tried to select a layer by "
> s<-sf$Unterregio".

'sf' is a data.frame-like object returned by read_sf, not a raster. If 's' is a 
raster, it could still contain multiple layers.

> > sf <- read_sf("C:/Users/._BiogeoRegion.shp")
> > names(sf)
> 
> > names(sf)
>  [1] "RegionNumm" "RegionName" "Unterregio" "Unterreg_1" "ObjNummer"
> "Version""Shape_Leng" "Shape_Area" "DERegionNa" "FRRegionNa"
> "ITRegionNa" "DEBioBedeu" "FRBioBedeu" "ITBioBedeu"
>  [15] "geometry"
> 
> > s<-sf$Unterregio
> > r<-allrasters_pres[[1]]

Sorry, that's still not enough information because we don't know what
names(rs) is. Since 'allrasters_pres' is a list of rasters, 'r' could also 
contain more than one layer, resulting in stack(r, s) containing more than two 
layers. 

In order to avoid the error, you need to see names(rs) and either give the same 
number of names to the object instead of two, or additionally extract one layer 
(using raster(r, layer = NUMBER_OR_NAME)) from each of 'r' and 's' before 
stacking them.

--
Best regards,
Ivan

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] boxplot of raster and shapefile

2024-08-26 Thread SIBYLLE STÖCKLI via R-help
Dear community

This example code works

library(raster)
library(sp)
library(rgdal)
library(ggplot2)

# Create some sample raster data
raster_file <- raster(ncol=36, nrow=18)
raster_file[] <- 1:ncell(raster_file)
plot(raster_file)

#Create some sample polygons
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
shape_file <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), 
  Polygons(list(Polygon(cds2)), 2)))
plot(shape_file)


# Extract raster values within the shapefile
extracted_values <- extract(raster_file, shape_file)


# Assuming the shapefile has multiple polygons and you want to create a
boxplot for each
data_list <- lapply(1:length(extracted_values), function(i) {
  data.frame(value = extracted_values[[i]], polygon = i)
})
data <- do.call(rbind, data_list)

# Create the boxplot
bp<-ggplot(data, aes(x = factor(polygon), y = value)) +
  geom_boxplot() +
  labs(x = "Polygon", y = "Raster Values") +
  theme_minimal()
bp



For my own dataset I encountered problems in reading in the polygons. 
The error message comes in the boxplot function

Here may shape file
> # load shape file including all layers and print layers
> shape_file<-shapefile("C:/Users/.BiogeoRegion.shp")
Warning message:
[vect] Z coordinates ignored 
> names(shape_file)
 [1] "RegionNumm" "RegionName" "Unterregio" "Unterreg_1" "ObjNummer"
"Version""Shape_Leng" "Shape_Area" "DERegionNa" "FRRegionNa"
[11] "ITRegionNa" "DEBioBedeu" "FRBioBedeu" "ITBioBedeu"
> str(shape_file)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
  ..@ data   :'data.frame': 12 obs. of  14 variables:
  .. ..$ RegionNumm: int [1:12] 1 2 2 2 2 3 3 4 5 5 ...
  .. ..$ RegionName: chr [1:12] "R1" "R2" "R2" "R2" ...
  .. ..$ Unterregio: int [1:12] 11 21 22 23 24 31 32 41 51 52 ...
  .. ..$ Unterreg_1: chr [1:12] "U11" "U21" "U22" "U23" ...
  .. ..$ ObjNummer : chr [1:12] "1" "2" "3" "4" ...
  .. ..$ Version   : chr [1:12] "2020/05/08" "2020/05/08" "2020/05/08"
"2020/05/08" ...
  .. ..$ Shape_Leng: num [1:12] 725117 334364 539746 576810 41 ...
  .. ..$ Shape_Area: num [1:12] 4.17e+09 1.11e+09 1.07e+09 4.64e+09 4.47e+09
...
  .. ..$ DERegionNa: chr [1:12] "Jura" "Mittelland" "Mittelland"
"Mittelland" ...
  .. ..$ FRRegionNa: chr [1:12] "Jura" "Plateau" "Plateau" "Plateau" ...
  .. ..$ ITRegionNa: chr [1:12] "Giura" "Altipiano" "Altipiano" "Altipiano"
...
  .. ..$ DEBioBedeu: chr [1:12] "Jura und Randen" "Genferseegebiet"
"Hochrheingebiet" "Westliches Mittelland" ...
  .. ..$ FRBioBedeu: chr [1:12] "Jura et Randen" "Bassin lémanique" "Bassin
rhénan" "Plateau occidental" ...
  .. ..$ ITBioBedeu: chr [1:12] "Giura e Randen" "Regione del Lemano"
"Regione dell’Alto Reno" "Altipiano occidentale" ...
  ..@ polygons   :List of 12


> # select a specific raster file from a list
> raster_file<-allrasters_pres[[1]]
> names(raster_file)
[1] "Andrena.barbilabris_glo_ensemble"
> 
> # Extract raster values within the shapefile
> extracted_values <- extract(raster_file, shape_file)
> 
> 
> 
> # Assuming the shapefile has multiple polygons and you want to create a
boxplot for each
> data_list <- lapply(1:length(extracted_values), function(i) {
+ data.frame(value = extracted_values[[i]], polygon = i)
+ })
> data <- do.call(rbind, data_list)

> names(data)
[1] "value"   "polygon"
> 
> # Create the boxplot
> bp<-ggplot(data, aes(x = factor(polygon), y = value)) +
+ geom_boxplot() +
+ labs(x = "Polygon", y = "Raster Values") +
+ theme_minimal()
> bp
Error in UseMethod("depth") : 
  no applicable method for 'depth' applied to an object of class "NULL"
In addition: Warning message:
Removed 452451 rows containing non-finite outside the scale range
(`stat_boxplot()`). 
>

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] boxplot of raster and shapefile

2024-08-28 Thread SIBYLLE STÖCKLI via R-help
max   : num 53

  .. .. ..@ band  : int 1

  .. .. ..@ unit  : chr ""

  .. .. ..@ names : chr "Andrena.barbilabris_glo_ensemble"

  ..@ legend  :Formal class '.RasterLegend' [package "raster"] with 5 slots

  .. .. ..@ type  : chr(0) 

  .. .. ..@ values: logi(0) 

  .. .. ..@ color : logi(0) 

  .. .. ..@ names : logi(0) 

  .. .. ..@ colortable: logi(0) 

  ..@ title   : chr(0) 

  ..@ extent  :Formal class 'Extent' [package "raster"] with 4 slots

  .. .. ..@ xmin: num 248

  .. .. ..@ xmax: num 284

  .. .. ..@ ymin: num 107

  .. .. ..@ ymax: num 130

  ..@ rotated : logi FALSE

  ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots

  .. .. ..@ geotrans: num(0) 

  .. .. ..@ transfun:function ()  

  ..@ ncols   : int 14400

  ..@ nrows   : int 9200

  ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot

  .. .. ..@ projargs: chr "+proj=somerc +lat_0=46.952405556 
+lon_0=7.439583 +k_0=1 +x_0=260 +y_0=120 +ellps=bessel +units=m 
+no_defs"

  .. .. ..$ comment: chr "PROJCRS[\"unknown\",\nBASEGEOGCRS[\"unknown\",\n  
  DATUM[\"Unknown based on Bessel 1841 ellipsoid\",\n"| __truncated__

  ..@ srs : chr "+proj=somerc +lat_0=46.952405556 
+lon_0=7.439583 +k_0=1 +x_0=260 +y_0=120 +ellps=bessel +units=m 
+no_defs"

  ..@ history : list()

  ..@ z   : list()

 

 

> e <- extract(r,v)

Error in (function (classes, fdef, mtable)  : 

  kann keine vererbte Methode finden für Funktion ‘extract’ für Signatur 
‘"RasterLayer", "SpatVector"’

 

 

Kind regards

Sibylle

 

-Original Message-
From: Ivan Krylov  
Sent: Tuesday, August 27, 2024 6:55 PM
To: SIBYLLE STÖCKLI via R-help 
Cc: sibylle.stoec...@gmx.ch
Subject: Re: [R] boxplot of raster and shapefile

 

В Mon, 26 Aug 2024 14:33:02 +0200

SIBYLLE STÖCKLI via R-help < <mailto:r-help@r-project.org> 
r-help@r-project.org> пишет:

 

> > # Extract raster values within the shapefile extracted_values <- 

> > extract(raster_file, shape_file)

 

> > # Assuming the shapefile has multiple polygons and you want to # 

> > create a boxplot for each data_list <- 

> > lapply(1:length(extracted_values), function(i) {

> + data.frame(value = extracted_values[[i]], polygon = i)

> + })

> > data <- do.call(rbind, data_list)

 

> > names(data)

> [1] "value"   "polygon"

> > # Create the boxplot

> > bp<-ggplot(data, aes(x = factor(polygon), y = value)) +  

> + geom_boxplot() +

> + labs(x = "Polygon", y = "Raster Values") +

> + theme_minimal()

> > bp  

> Error in UseMethod("depth") : 

>   no applicable method for 'depth' applied to an object of class

> "NULL"

> In addition: Warning message:

> Removed 452451 rows containing non-finite outside the scale range

> (`stat_boxplot()`). 

 

Thank you for providing a runnable example! Could you please also show

the output of str(extracted_values) and str(data)?

 

-- 

Best regards,

Ivan


[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] foreSIGHT package

2024-11-02 Thread Sibylle Stöckli via R-help
Dear community

I have started to use the foreSIGHT package fo calculate some climatic 
indicators.

Example
library(foreSIGHT)
func_avgDSD(WAAR$Ta, attArgs)

Dataset (WAAR, Ta = average daily temperature)
Year DOY Ta
1990 1 -2.45
1990 2 1.54
.
.
2001 1 4.54
,
2001 205 15.65
2001 206 20.14
.
2001 365 8.65
..
2023 1 0.45


Questions:
Is it possible to run the foreSIGHT with DOY numbers not dates (e.g. 1983-04-09 
23.64) and additionally separate years? 
 
I have some problems to understand attArgs. Up to now I have not found any 
reference. How do I need to prepare the list? And where I can set the threshold?
 
Sometimes there are indicators without any definition of the threshold? E.g. 
cold seasons length: func_CSL (data) how is a cold day defined here (the 
threshold for cold days), there is no attArgs?

Many thanks 
Sibylle



[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


[R] Using multiple dat files

2024-11-06 Thread Sibylle Stöckli via R-help
Dear community

To import multiple .dat  weather files I am using list.files().
I intend to use the R package “ClimInd” to calculate different agroclimatic 
indicators. 

Question: Is there another solution to import multiple .dat files so that I can 
select elements from the list, e.g. one specific weather file (example 
AAR_DailyWeather)?
 
 
# Import multiple .dat files weather data
filelist <- list.files(path = "O:/Data-Work/……./Daten_RA-MeteoCH_1990-2021", 
pattern='*.dat', all.files= T, full.names= T)
W <- lapply(filelist, function(x) read.table(x, header = TRUE, sep = "", 
colClasses = "numeric", comment.char = ""))
W[[1]]
 
> dd(data = W[[1]]$Precip, time.scale = W[[1]]$year)
Fehler in W[[1]]$year : $ operator is invalid for atomic vectors
 
Kind regards
Sibylle
 
 
 
__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.