繁体   English   中英

在ggplot中使用条形图时出现意外的x轴刻度线

[英]Unexpected x axis tick marks when using bar chart in ggplot

我正在尝试在ggplot中创建一个条形图,以显示特定日期在两个不同位置的利润。

这是我正在使用的代码:

test_data <- data.frame("location" = c('location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2',
                                   'location_1', 'location_2'), 
                      "date" = c(as.Date('2018-07-29'), as.Date('2018-07-29'), 
                               as.Date('2018-07-30'), as.Date('2018-07-30'), 
                               as.Date('2018-08-02'), as.Date('2018-08-02'), 
                               as.Date('2018-08-03'), as.Date('2018-08-03'), 
                               as.Date('2018-08-05'), as.Date('2018-08-05'),
                               as.Date('2018-08-08'), as.Date('2018-08-08'),
                               as.Date('2018-08-12'), as.Date('2018-08-12'), 
                               as.Date('2018-08-15'), as.Date('2018-08-15'), 
                               as.Date('2018-08-19'), as.Date('2018-08-19')),
                    "profit" = c(540, 120, 265, 493, 245, 432, 987, 566,
                                 654, 765, 234, 767, 650, 765, 874, 652,
                                 175, 497), 
                    stringsAsFactors = FALSE) 

sundays <- c(as.Date('2018-07-29'),as.Date('2018-08-05'),
             as.Date('2018-08-12'),as.Date('2018-08-19'))

test_data %>% 
filter(date %in% sundays) %>% 
ggplot(aes(x=date, y=profit)) + 
geom_bar(stat = 'identity') +
xlab('Date') +
ylab('Profit') + 
facet_wrap(~location)

因此,我想创建一个仅显示星期日的图形,但绘制时会将错误的日期与条形关联。

图示例

我该如何解决? 提前致谢!

检查此解决方案:

test_data %>%
  filter(date %in% sundays) %>%
  mutate(date = date %>% as.character()) %>%
  ggplot(aes(x=date, y=profit)) + 
  geom_bar(stat = 'identity') +
  xlab('Date') +
  ylab('Profit') + 
  facet_wrap(~location) +
  scale_x_discrete(
    labels = function(x) x %>% as.Date() %>% format('%b %d')
  )

在评论中回答问题:

我发现了一些“肮脏的骇客”,但不确定是否在所有情况下都可以使用。 检查并让我知道。

library(tidyverse)
library(wrapr)

test_data %>%
  filter(date %in% sundays) %>%
  arrange(date) %>%
  group_by(location) %>%
  mutate(
    xpos = row_number(),
    xlab = if_else(xpos %% 2 == 0, '', date %>% as.Date() %>% format('%b %d'))
  ) %.>%
  ggplot(
    data = .,
    aes(x = factor(xpos), y = profit)
  ) + 
  geom_bar(stat = 'identity') +
  xlab('Date') +
  ylab('Profit') + 
  facet_wrap(~location) +
  scale_x_discrete(
    breaks = .$xpos,
    labels = .$xlab 
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM