Curves with ggplot2


I have a function f(p,q) which returns a vector of numbers.
I would like to plot the curve f for all the values of p and q that I have.
For instance, if p=(2,3,4) and q=(1,5,2), I would like the 3 plots f(2,1) ; f(3,5) and f(4,2) on the same graph with 3 different colors, and the legend that fits.

Thanks for the answers.

f <- function(p, q) {
  sin((1:10) * p) + q

(my_data <- tibble(
  p = 2:4,
  q = c(1, 5, 2)

(my_plot_data <- my_data |> rowwise() |> mutate(y = list(f(p, q))) |>
  unnest_wider(col = y, names_sep = "_") |> pivot_longer(
    cols = starts_with("y_"), names_to = "x_",
    values_to = "y"
  ) |> mutate(
    x = parse_number(x_),
    pq_label = glue("f({p},{q})")

ggplot(data = my_plot_data) +
  aes(x = x, y = y, color = pq_label) +

1 Like

Wonderful, thanks a lot !

Is it possible to have the color and the type of line (dashed...) changing for each curve ? (that's possibly for a print without color as well). I have no differences adding "linetype".

ggplot(data = my_plot_data) +
  aes(x = x, y = y, color = profiles, linetype=profiles) +

Yes, in ggplot it's done with scale_* functions

Still no difference for the legend. Is it normal ?

ggplot(data = my_plot_data) +
  aes(x = x, y = y, color = profiles, linetype=profiles) +
  geom_line(linewidth=2)+ scale_linetype_manual(values=c("twodash", "dotted","longdash","solid"))+
  scale_color_manual(values=c('red','blue','green','black'))+  theme(legend.position="right")

1 Like

Anyway, I will create another topic if needed. The problem I came here in the first place is successfully solved. Thanks to @nirgrahamuk.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.