R ggplot2使用stat_summary为分类数据设置x轴限制

时间:2018-08-03 18:27:48

标签: r ggplot2 graph axis

在对分类变量调用ggplot2::stat_summary()之后,如何显式设置x轴的比例?

我正在尝试设置x轴的开始和结束值。我已经将因子变量映射到x,但是我无法使scale_x_discrete()正常工作。这是因为我使用统计信息层计算了meanmean_sdl吗?

这是my goal。但是,以下代码

library(ggplot2)
data(barley, package = "lattice")
# Ribbon plot: depicting overlapping measures of spread
ggplot(barley, aes(x = year, y = yield, col = site, fill = site, group = site)) +

# Create mean yield as line
stat_summary(fun.y = mean,
             geom = "line",
             size = 1) +

# Show standard deviation of each site
stat_summary(fun.data = mean_sdl,
             fun.args = list(mult = 1),
             geom = "ribbon",
             col = NA,
             alpha = 0.1) +

# Scale axes
scale_y_continuous(limits = c(0, 70), breaks = seq(0, 70, by = 10)) +
scale_x_discrete(limits = c("1932", "1931"), breaks = c("1932", "1931")) +

# Make pretty
labs(x = "Year", y = "Yield (bushels/acre)", col = "Site", fill = "Site") +
theme(panel.background = element_blank(),
      axis.line.x.bottom = element_line(color = "black"),
      axis.line.y.left = element_line(color = "black")
)

生成this graph。我希望我的x轴从1932年开始,到1931年结束。

我可以用x来改变as.integer(year)的美感,然后调用scale_x_continuous(),但这似乎是很多额外的工作。

更新

expand = c(0, 0)调用中添加scale_x_discrete可以解决此问题。

0 个答案:

没有答案