datetime时在x轴刻度线之后开始的条

datetime时在x轴刻度线之后开始的条

本文介绍了使用scale_x_datetime时在x轴刻度线之后开始的条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用条形图绘制每小时数据时,条形图被X点的X轴刻度线除以.数据对应于6-7点,7-8点,依此类推.我希望每个小节都从x点开始,而不是从x-0:30分钟开始.

When i use a barplot to plot hourly data, the bars are divided by the x-axis tickmark at X o´clock sharp. The data corresponds to 6-7 o´clock, 7-8 o´clock and so on.I want each bar to start at x o´clock sharp and not at x - 0:30 min.

代码示例:

install.packages("nycflights13")
library(nycflights13)
data <- flights %>% select(time_hour, hour) %>%
                    mutate(flightdate = floor_date(time_hour, "day")) %>%
                    filter(flightdate == as_date("2013-01-01")) %>% group_by(flightdate,hour) %>% tally() %>%
                    mutate(flightdatetime = as_datetime(paste(flightdate + hours(hour)))) %>%
                    select(flightdatetime,n)

ggplot() +
  geom_col(aes(x=flightdatetime, y = n),
           data = data, color = "black", fill = "black") +
  ggplot2::scale_x_datetime(labels = date_format("%H:%M", tz = "Europe/Berlin"), date_breaks = "1 hour")  +
  theme_minimal() + labs(title ="Flights per hour")

推荐答案

这是怎么回事:

ggplot() +
      geom_bar(aes(x=flightdatetime, y = n),stat="identity",
               data = data, color = "black", fill = "black") +
      ggplot2::scale_x_datetime(labels = date_format("%H:%M", tz = "Europe/Berlin"), date_breaks = "1 hour", expand=c(0, .9))  +
      theme_minimal() + labs(title ="Flights per hour") +
      theme(axis.text.x = element_text(hjust=1.5))

我使用 theme(axis.text.x = element_text(hjust = 1.5))将标签向左移动,而 expand = c(0,.9) scale_x_datetime 内剪切第一个和最后一个轴标签.您可以玩这两个,看看是否合适.

I used theme(axis.text.x = element_text(hjust=1.5)) to move the labels to the left and expand=c(0, .9) inside scale_x_datetime to cut the first and last axis labels.You can play with this two and see if it fits.

这篇关于使用scale_x_datetime时在x轴刻度线之后开始的条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:34