Reputation: 168
I am melting a data frame in order to plot it in ggplot2. However,
geom_line()
is not giving me horizontal lines. Instead it is transforming my points to vertical lines. I will attach images and add the code to further illustrate:
Using only geom_point()
:
vecmmelt = melt(tail(tempdf,7), id.vars = "Date")
ggplot(vecmmelt, aes(x = Date, y = value, colour = variable, group=1)) +geom_point()+theme_bw()
Now I would expect to have the following when using geom_line()
:
What I am really getting by using the following code is the following picture:
vecmmelt = melt(tail(tempdf,7), id.vars = "Date")
ggplot(vecmmelt, aes(x = Date, y = value, colour = variable, group=1)) +geom_point()+geom_line()
I tried using geom_path()
and it also is wrong
Upvotes: 4
Views: 9707
Reputation: 67
This is not because of your variable grouping, but because your date format is not correct. Instead of it understanding it as d-M-Y, it is understanding it as M-d-Y, so you have many values for each months but not days in between. Try reformating your date:
df$Date <-as.Date(paste(df$Year, df$Momnth, 01), "%Y %m %d")
Upvotes: 0
Reputation: 1424
It looks like the problem is that you are specifying group=1
, which tells ggplot to connect all the dots. As Mario Barbé explained for a similar question:
For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.
Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
So, in your case, you should specify group=variable
to fix the issue.
Upvotes: 3