[R] How to plot both lines and points by group on ggplot2

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sat Jul 1 21:24:14 CEST 2023

```Às 19:20 de 01/07/2023, Luigi Marongiu escreveu:
> Hello,
> I have a dataframe with measurements stratified by the concentration
> of a certain substance. I would like to plot the points of the
> measures and connect the points within each series of concentrations.
> When I launch ggplot2 I get the error
> ```
> geom_path: Each group consists of only one observation. Do you need to
> adjust the
> group aesthetic?
> ```
> and no lines are drawn.
> Where am I going wrong?
> Thank you
> Luigi
>
> ```
> df = data.frame(Conc = c(rep(1, 3), rep(2, 3), rep(5, 3)),
>                  Time = rep(1:3, 3),
>                  Value = c(0.91, 0.67, 0.71, 0.91, 0.65, 0.74, 0.95, 0.67, 0.67))
> df\$Time <- as.factor(df\$Time)
> levels(df\$Time) = c(1, 4, 24)
> df\$Conc <- as.factor(df\$Conc)
> levels(df\$Conc) = c(1, 2, 5)
> library(ggplot2)
> ggplot(df, aes(x=Time, y=Value, colour=Conc)) +
>    geom_point(size=6) +
>    geom_line(aes(x=Time, y=Value, colour=Conc)) +
>    scale_colour_manual(values = c("darkslategray3", "darkslategray4",
>                                   "deepskyblue4")) +
>    ggtitle("Working example") +
>    xlab(expression(bold("Time (h)"))) +
>    ylab(expression(bold("Concentration (mM)")))
> ```
Hello,

Here are two solutions. I have removed the redundant aes() from
geom_line in both plots.

1. If you do not coerce Time to factor, the x axis will be continuous.
The plot will be as expected but you wi have to include a
scale_x_continuous to have the wanted labels.

df = data.frame(Conc = c(rep(1, 3), rep(2, 3), rep(5, 3)),
Time = rep(1:3, 3),
Value = c(0.91, 0.67, 0.71, 0.91, 0.65, 0.74, 0.95,
0.67, 0.67))

library(ggplot2)

df\$Conc <- factor(df\$Conc, levels = c(1, 2, 5))

ggplot(df, aes(x=Time, y=Value, colour=Conc)) +
geom_point(size=6) +
geom_line() +
scale_colour_manual(values = c("darkslategray3", "darkslategray4",
"deepskyblue4")) +
scale_x_continuous(breaks = 1:3, labels = c(1, 2, 24)) +
ggtitle("Working example") +
xlab(expression(bold("Time (h)"))) +
ylab(expression(bold("Concentration (mM)")))

2. Time is coerced to factor. Then, tell geom_line the data is grouped
by Conc. This is probably the solution you should use.

df\$Time <- factor(df\$Time, labels = c(1, 4, 24))

ggplot(df, aes(x=Time, y=Value, colour=Conc)) +
geom_point(size=6) +
geom_line(aes(group = Conc)) +
scale_colour_manual(values = c("darkslategray3", "darkslategray4",
"deepskyblue4")) +
ggtitle("Working example") +
xlab(expression(bold("Time (h)"))) +
ylab(expression(bold("Concentration (mM)")))

Hope this helps,

Rui Barradas

```

More information about the R-help mailing list