在 ggplot2 中的 X 轴上格式化日期 [英] Formatting dates on X axis in ggplot2
问题描述
我很难让 x 轴在我的图表中看起来正确.
I'm having a very, very tough time getting the x-axis to look correct for my graphs.
这是我的数据(通过 dput()
生成):
Here is my data (generated via dput()
):
df <- structure(list(Month = structure(1:12, .Label = c("2011-07-31", "2011-08-31", "2011-09-30", "2011-10-31", "2011-11-30", "2011-12-31", "2012-01-31", "2012-02-29", "2012-03-31", "2012-04-30", "2012-05-31", "2012-06-30"), class = "factor"), AvgVisits = c(6.98655104580674,7.66045407330464, 7.69761337479304, 7.54387561322994, 7.24483848458728, 6.32001400498928, 6.66794871794872, 7.207780853854, 7.60281201431308, 6.70113837397123, 6.57634103019538, 6.75321935568936)), .Names = c("Month","AvgVisits"), row.names = c(NA, -12L), class = "data.frame")
这是我要绘制的图表:
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar() +
theme_bw() +
labs(x = "Month", y = "Average Visits per User")
该图表工作正常 - 但是,如果我想调整日期的格式,我相信我应该添加以下内容:scale_x_date(labels = date_format("%m-%Y"))
That chart works fine - but, if I want to adjust the formatting of the date, I believe I should add this:
scale_x_date(labels = date_format("%m-%Y"))
我正在努力使日期标签为MMM-YYYY"
I'm trying to make it so the date labels are 'MMM-YYYY'
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar() +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
当我绘制它时,我继续收到此错误:
When I plot that, I continue to get this error:
stat_bin:binwidth 默认为 range/30.使用 'binwidth = x' 来调整它.
尽管对 geom_line
和 geom_bar
的格式进行了数小时的研究,我还是无法修复它.谁能解释我做错了什么?
Despite hours of research on formatting of geom_line
and geom_bar
, I can't fix it. Can anyone explain what I'm doing wrong?
作为后续想法:您可以使用日期作为一个因素,还是应该在日期列上使用 as.Date
?
As a follow-up thought: Can you use date as a factor, or should you use as.Date
on a date column?
推荐答案
你能用日期作为一个因素吗?
Can you use date as a factor?
是的,但您可能不应该这样做.
Yes, but you probably shouldn't.
...或者你应该在日期列上使用 as.Date
吗?
...or should you use
as.Date
on a date column?
是的.
导致我们这样做:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
其中我已将 stat = "identity"
添加到您的 geom_bar
调用中.
in which I've added stat = "identity"
to your geom_bar
call.
此外,有关 binwidth 的消息不是错误.错误实际上会在其中说错误",同样,警告总是会在其中说警告".否则,它只是一条消息.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
这篇关于在 ggplot2 中的 X 轴上格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!