gpt4 book ai didi

R:在 ggplot 中为 yearqtr(动物园)设置 scale_x_yearqtr 的限制

转载 作者:行者123 更新时间:2023-12-04 05:37:26 33 4
gpt4 key购买 nike

我正在使用类似于以下摘录的数据集:

head(nomis.lng.agg)
quarter decile avg.val
1 2004 Q4 1 5.680000
2 2005 Q1 1 5.745763
3 2005 Q2 1 5.503341
4 2005 Q3 1 5.668224
5 2005 Q4 1 5.244604
6 2006 Q1 1 5.347222

变量季度是类 yearqtrzoo 生成.剩下的两列是数字。我目前正在生成一个使用以下内容的图 ggplot句法:
ggplot(data = subset(x = df,
subset = df$decile== 1 |
df$decile== 10),
aes(x = quarter, y = avg.val, group = decile)) +
geom_line(aes(linetype=as.factor(decile)),
size = 1) +
scale_x_yearqtr(format = "%YQ%q", n = 5) +
xlab("Quarter") +
ylab("Average val") +
ggtitle("Plot") +
scale_linetype_discrete(name="Legend") +
theme(panel.background = element_blank(),
axis.line = element_line(colour = "black"),
axis.text = element_text(size = 12, colour = "black"),
axis.title = element_text(size = 14, colour = "black"),
panel.grid.minor = element_blank(),
panel.grid.major.y = element_line(colour = "gray"),
panel.grid.major.x = element_blank(),
axis.text = element_text(size = 12, colour = "black"),
legend.text = element_text(size = 12),
legend.title = element_text(size = 12),
legend.key.width=unit(1.5,"cm"),
legend.position = "bottom",
legend.key = element_rect(fill = "white"),
legend.background = element_rect(colour = "black"),
plot.title = element_text(face="bold"),
plot.background = element_rect(colour = "black"))

除了 x 轴外,该图几乎是完美的。当前的 x 轴如下所示:
broken axis

我的重点是代码 scale_x_yearqtr(format = "%YQ%q", n = 5) .因为我的数据从 开始2004年第四季度我对绘图不感兴趣 2004年第一季度 ,但我想设置限制:
scale_x_yearqtr(format = "%YQ%q", 
limits=c(min(quarter), max=max(quarter)))

然而,这并没有产生预期的结果,尽管:
min(df$quarter)
[1] "2004 Q4"

最佳答案

我想你只是没有指定 limits适本地。此外,为了更好地控制外观,请使用 breaks参数(而不是 n )。

# some data
df <- data.frame(x = as.yearqtr(2004 + seq(3, 8)/4), y = sample(1:6))

# setting limits only
ggplot(data = df, aes(x, y, group = 1)) +
geom_line() +
scale_x_yearqtr(limits = c(min(df$x), max(df$x)),
format = "%YQ%q")

enter image description here
# setting breaks
ggplot(data = df, aes(x, y, group = 1)) +
geom_line() +
scale_x_yearqtr(breaks = seq(from = min(df$x), to = max(df$x), by = 0.25),
format = "%YQ%q")

enter image description here

关于R:在 ggplot 中为 yearqtr(动物园)设置 scale_x_yearqtr 的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28679055/

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