72

Suppose I have a dataframe:

hist <- data.frame(date=Sys.Date() + 0:13, counts=1:14) 

I want to plot the total count against weekday, using a line to connect the points. The following puts points on each value:

hist <- transform(hist, weekday=factor(weekdays(date), levels=c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'))) ggplot(hist, aes(x=weekday, y=counts)) + geom_point(stat='summary', fun.y=sum) 

When I try to connect them with a line (geom_line()), ggplot complains about only having one data observation per group and hence is not able to draw a line between the points.

I understand this - it's trying to draw one line for each weekday (factor level).

How can I get ggplot to just pretend (for the purposes of the line only) that the weekdays are numeric? Perhaps I have to have another column day_of_week that is 0 for monday, 1 for tuesday, etc?

2 Answers 2

80

If I understand the issue correctly, specifying group=1 and adding a stat_summary() layer should do the trick:

ggplot(hist, aes(x=weekday, y=counts, group=1)) + geom_point(stat='summary', fun.y=sum) + stat_summary(fun.y=sum, geom="line") 

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Fantastic! What is the purpose of group=1 (why 1? what does that do?)
Oh, I think I found it. here (ggplot2 documentation)
In case you want to plot multiple lines at once, you should specify `group=variableWhichDefinesLines'
2

A solution that worked for me very easily was:

ggplot(data.frame, aes(X, Y)) + geom_point() + geom_path(group=1) + theme(axis.text.x = element_text(angle=90, hjust = 1, vjust = 0.5)) 

group = 1 lets ggplot know that you want to treat all the observations as part of the same group, and will therefore draw the line. The theme line is just for a cleaner look. You can delete it if you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.