Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

r - Using `geom_line()` with X axis being factors

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...