如何使用ggplot在x轴上添加更多数量的标签

问题描述 投票:1回答:1

我有以下图表,但是我想在x axis上添加其他标签。

我已经尝试过scale_x_continuous,但它不起作用,因为我的值不是数字值,而是日期。

我该如何解决?

enter image description here

r plot ggplot2 axis
1个回答
2
投票

如果用“更多x值”表示您希望在x轴上有更多标签,则可以使用scale_x_dates参数来调整频率,如下所示:

scale_x_date(date_breaks = "1 month", date_labels = "%b-%y")

这是我的工作示例。如果我误解了您的问题,请发表您自己的文章:

library("ggplot2")
# make the results reproducible
set.seed(5117)  

start_date <- as.Date("2015-01-01") 
end_date <- as.Date("2017-06-10")

# the by=7 makes it one observation per week (adjust as needed)
dates <- seq(from = start_date, to = end_date, by = 7)
val1 <- rnorm(length(dates), mean = 12.5, sd = 3)

qnt <- quantile(val1, c(.05, .25, .75, .95))

mock <- data.frame(myDate = dates, val1)

ggplot(data = mock, mapping = aes(x = myDate, y = val1)) +
  geom_line() +
  geom_point() +
  geom_hline(yintercept = qnt[1], colour = "red") +
  geom_hline(yintercept = qnt[4], colour = "red") +
  geom_hline(yintercept = qnt[2], colour = "lightgreen") +
  geom_hline(yintercept = qnt[3], colour = "lightgreen") +
  theme_classic() +
  scale_x_date(date_breaks = "1 month", date_labels = "%b-%y") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.