0

Here's the image of my problem

I want to have a line to connect the points here.

Here is the code I have used:

library(dplyr)
library(ggplot2)
library(readr)

# Create a line chart with markers
ggplot(df, aes(x = USER_ALLIAS , y = AVERAGE_HEART_RATE)) +
  geom_line(color = "blue", linetype = "solid") +
  geom_point(color = "blue") +
  geom_line(aes(y = MAXIMUM_HEART_RATE), color = "red") +
  geom_point(aes(y = MAXIMUM_HEART_RATE), color = "red") +
  #Connect the points
  geom_path(aes(x = USER_ALLIAS, y = AVERAGE_HEART_RATE), color = "blue", linetype = "sold") +
  geom_path(aes(x = USER_ALLIAS, y = MAXIMUM_HEART_RATE), color = "red") +
  labs(title = "Average and Maximum Heart Rate per User", x = "User ID", y = "Heart Rate") `

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    Welcome to SO! With no data and no plot, it's difficult to see your problem! – Limey Aug 17 '23 at 10:03
  • Hello! I have just attached the image of my problem to see it. Thank you. – Jhon Paul Gervacio Aug 17 '23 at 10:10
  • I suspect the problem is that your `USER_ALLIAS` is character. That means `ggplot2` is treating it as a factor and so there is only a single point in each group, and thus nothing to "join up" when drawing the lines. Convert your user ids to numerics and adjust the labelling of the x axis if necessary. – Limey Aug 17 '23 at 10:14
  • Incidentally, your data is not tidy, which is making your life more difficult than it needs to be. `ggplot2` as part of ther tidyverse, expects tidy data. To make your data frame tidy, use `pivot_wider` to put `AVERAGE_HERAT_RATE` and ~MAXIMUM_HERT_RATE` in a single column and use a new column, `Type` say, to distinguish between the two summaries. You can the use `aes(colour = Type)` to draw multiple lines in a single `geom_xxx` call. Your code will be shorter, more rubust and easier to understand and maintain. – Limey Aug 17 '23 at 10:16
  • Thank you so much! I will try that approach. – Jhon Paul Gervacio Aug 17 '23 at 10:16
  • 1
    ... or set the `group` aesthetic, i.e. do `geom_line(aes(group = 1), color = "blue")` and `geom_line(aes(y = MAXIMUM_HEART_RATE, group = 1), color = "red")` – stefan Aug 17 '23 at 10:17
  • @stefan true, though I believe that's treating the symptom not the underlying condition. – Limey Aug 17 '23 at 10:19
  • @Limey Reshaping to long is the easier way to create the plot. But we still have to use the `group` aes. And IMHO we are not treating any symptoms since from the perspective of tidy data the data is already tidy as the average and maximum are two different variables. – stefan Aug 17 '23 at 10:31

0 Answers0