[R] arrow on contour line
Lennart Kasserra
|enn@rt@k@@@err@ @end|ng |rom gm@||@com
Thu Jan 11 09:54:04 CET 2024
Hi,
If I understand your intentions correctly, the simplest way would be to
manually insert arrows using `geom_segment()` with the `arrow` argument:
```
ggplot(data = d1, aes(x=X1,y=X2,z=Z))+
stat_contour(breaks = c(2)) +
stat_contour(data=d2, aes(x=X1,y=X2,z=Z), breaks=c(6)) +
geom_segment(
aes(x = 1.25, y = 1.50, xend = 1.4, yend = 1.325),
arrow = arrow(length = unit(0.5, "cm"))
) +
geom_segment(
aes(x = 1.6, y = 1.95, xend = 1.8, yend = 1.75),
arrow = arrow(length = unit(0.5, "cm"))
)
```
If your actual data is organized differently, you may also be able to do
this in a more elegant programmatic way. Here is a StackOverflow
conversation about this exact topic, one Google search away:
https://stackoverflow.com/questions/38008863/how-to-draw-a-nice-arrow-in-ggplot2
Have a nice day,
Lennart Kasserra
Am 11.01.24 um 01:13 schrieb Deepankar Basu:
> Hello,
>
> I am drawing contour lines for a function of 2 variables at one level of
> the value of the function and want to include a small arrow in any
> direction of increase of the function. Is there some way to do that?
>
> Below is an example that creates the contour lines. How do I add one small
> arrow on each line in the direction of increase of the function (at some
> central point of the contour line)? Any direction will do, but perhaps the
> direction of the gradient will be the best.
>
> Thanks in advance.
> DB
>
> --------------------------------------------
>
> library(tidyverse)
>
> x <- seq(1,2,length.out=100)
> y <- seq(1,2,length.out=100)
>
> myf <- function(x,y) {x*y}
> myg <- function(x,y) {x^2 + y^2}
>
> d1 <- expand.grid(X1 = x, X2 = y) %>%
> mutate(Z = myf(X1,X2)) %>%
> as.data.frame()
>
> d2 <- expand.grid(X1 = x, X2 = y) %>%
> mutate(Z = myg(X1,X2)) %>%
> as.data.frame()
>
> ggplot(data = d1, aes(x=X1,y=X2,z=Z))+
> stat_contour(breaks = c(2)) +
> stat_contour(data=d2, aes(x=X1,y=X2,z=Z), breaks=c(6))
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using 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.
More information about the R-help
mailing list