2

I learned from stack overflow that geom_path() can remove the line from different part of data on the same line. It means that inside the whole Red line, there are some other colors parts, and without this command, the last point at previous blue part is linked to the first point in next blue part. Code and image are as below:

p6 <- ggplot(data = M1.m, mapping = aes(x = as.Date(M1_Date, format='%d/%m/%Y'), 
                                       y = M1_Value, color = factor(NewGroup))) + geom_path(aes(group = 1)) + geom_point(size = 0.5)
p6 <- p6 + labs(x = "Date", y = "Value") + labs(color = "Value Type")
p6

enter image description here

When I use them, it seems that interval data has solved this questions, but there is a wired line linked between the first data and the last data. Can you please tell me how to remove that?

The data is too large and I cannot link here sorry about that and here is the link: Data

Thank you!

Ericshaw
  • 51
  • 6

2 Answers2

0

The geom_path() is used to draw line according to data order in data frame. In my question, column M1_value includes two types data with same period. So the last data in type 1 is next to the first data in type, and that's the reason for the wired line. The solution is to add a new column (say type) in data frame and add group = type in aes() to remove line. (BTW, this question is similar as recording monthly temperature because first day of new month's temperature will be linked by temperature of the last day of month, and the key for this type of question is to specify classification clearly and group them makes the question more easier.)

Answer: Change previous code to:

p6 <- ggplot(data = M1.m, mapping = aes(x = as.Date(M1_Date, format='%d/%m/%Y'), y = M1_Value, 
                                        color = NewGroup, group = M1_Type)) + geom_path() + geom_point(size = 0.5)
p6 <- p6 + labs(x = "Date", y = "Value") + labs(color = "Value Type")
p6

and the plot changes to: M1 So the wired line is removed. Done! Thanks for the help from following link: R geom_path lines "closing", sometimes. How to keep them "open"?.

Ericshaw
  • 51
  • 6
0

For me, a simpler solution was to arrange the dataframe using the variable plotted on the x-axis. In the example above, this would result in:

p6 <- ggplot(data = M1.m %>% arrange(M1_Date), mapping = aes(x = as.Date(M1_Date, format='%d/%m/%Y'), 
                                       y = M1_Value, color = factor(NewGroup))) + geom_path(aes(group = 1)) + geom_point(size = 0.5)
p6 <- p6 + labs(x = "Date", y = "Value") + labs(color = "Value Type")
p6

I haven't tested this on the data above. The solution given by Ericshaw did not work for me because I could not add a group aesthetic when already using linetype as an aesthetic.

KyraC
  • 1