gpt4 book ai didi

r - scale_x_date 删除轴上的额外月份(ggplot2 2.2.0.9)

转载 作者:行者123 更新时间:2023-12-01 12:24:09 24 4
gpt4 key购买 nike

我正在使用带有时间刻度的折线图,最后一点是 12 月 30 日。但是,对于 scale_x_date,即使有该月的数据点,1 月也会显示在比例尺上。

规模应该真正停止在上个月,但我相信这是因为这一天。有没有办法让规模坚持数据中的实际月份?

我正在使用它来格式化比例:

#with lubridate
data$month <- ymd(data$month)

#in the plot
scale_x_date(date_breaks = "1 month", date_labels ="%b %y")

可重现的例子:
library(lubridate)
library(ggplot2)

cities <- c("city1")
month <- c("2016-08-01", "2016-09-30", "2016-10-30", "2016-11-30", "2016-12-30")
num <- c(23287, 23889, 25026, 26116, 29758)

data <- data.frame(cities, month, num)
data$month <- ymd(data$month)

gg <- ggplot(data, aes(month, num, group = 1)
gg <- gg + geom_line(position = "identity", color="#6baed6")
gg <- gg + scale_y_continuous(expand = (c(0.1,0)))
gg <- gg + scale_x_date(expand = c(0, 0), date_labels ="%b %y")
gg <- gg + labs(x = NULL, y = NULL)
gg <- gg + theme(strip.background=element_blank())
gg <- gg + theme_bw()
gg <- gg + theme(panel.border = element_blank())
gg <- gg + theme(panel.grid.major = element_blank())
gg <- gg + theme(panel.grid.minor = element_blank())
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(axis.text.x=element_text(size=12))
gg <- gg + theme(axis.text.y=element_text(size=12))
gg

在此示例中,如果没有 expand(),即使一月没有数据点,也会添加一月。

每月有一个数据点,我的目标是按月显示数据。我可以转换为因子,但这并不理想。我知道数据有一天,但肯定必须有办法做到这一点。

最佳答案

我不认为这是一个好情节,但你来了。您可能希望将休息时间设置为每个月的第 15 天:

library(ggplot2)
ggplot(data, aes(month, num, group = 1)) +
geom_line(position = "identity", color="#6baed6") +
#scale_y_continuous(expand = (c(0.1,0)), labels = comma) +
scale_x_date(breaks = seq(as.Date("2016-07-15"),
as.Date("2016-12-15"), by = "1 month"), date_labels ="%b %y") +
labs(x = NULL, y = NULL) +
theme_bw() +
theme(strip.background=element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
axis.ticks=element_blank(),
axis.text=element_text(size=12))

resulting plot

关于r - scale_x_date 删除轴上的额外月份(ggplot2 2.2.0.9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com