【问题标题】:How to add more number of labels on x-axis using ggplot如何使用ggplot在x轴上添加更多标签
【发布时间】:2017-05-16 14:58:39
【问题描述】:

我有以下情节,但我想在x axis 上添加其他标签。

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

我该如何解决这个问题?

【问题讨论】:

  • “更多 x 值”,如更多日期时间点?你能否也展示你正在使用的代码,也许还有一些示例数据?
  • 你看过scale_x_date吗?您可以使用breaks = ... 选项指定更多中断
  • 我认为问题在于 R 无法注意到该列是日期格式,即使我在导入过程中手动更改为日期。当我查看文档时更改为未知。
  • @Ana Raquel:以下解决方案适用于您的情况吗?
  • 是的@Stan,谢谢!

标签: r plot ggplot2 axis


【解决方案1】:

如果“更多 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多