使用 `geom_line()` 和 X 轴作为因子 [英] Using `geom_line()` with X axis being factors
问题描述
假设我有一个数据框:
hist <- data.frame(date=Sys.Date() + 0:13,计数 = 1:14)
我想根据工作日绘制总计数,使用线连接点.以下将点放在每个值上:
hist <- transform(hist, weekday=factor(weekdays(date),level=c('星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日')))ggplot(hist, aes(x=weekday, y=counts)) + geom_point(stat='summary', fun.y=sum)
当我尝试用一条线 (geom_line()
) 将它们连接起来时,ggplot 抱怨每组只有一个数据观察,因此无法在点之间画一条线.>
我理解这一点 - 它试图为每个工作日(因素级别)画一条线.
我怎样才能让 ggplot 假装(仅用于行)工作日是数字?也许我必须有另一列 day_of_week
星期一为 0,星期二为 1,等等?
如果我正确理解问题,指定 group=1
并添加 stat_summary()
层应该做伎俩:
ggplot(hist, aes(x=weekday, y=counts, group=1)) +geom_point(stat='summary', fun.y=sum) +stat_summary(fun.y=sum, geom="line")
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?
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")
这篇关于使用 `geom_line()` 和 X 轴作为因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!