使用ggplot scale_x_yearmon缺少yearmon标签

时间:2019-02-08 11:38:49

标签: r ggplot2 graph zoo

我已经按月和年对一些数据进行了分组,使用Zoo转换为Yearmon,现在将其绘制在ggplot中。有谁知道为什么缺少一个勾号标签,而当月没有数据的情况下,在2018-07年度没有一个勾号标签?

示例数据:

//Responses from the REST service go to this channel
@Bean("marketingCategory")
MessageChannel marketingCategory() { return new PublishSubscribeChannel();}

//This channel is used to trigger the outbound gateway which makes a request to the REST service
@Bean
MessageChannel marketingCategoryPoller() {return new DirectChannel();}

//An adapter creating triggering messages for the gateway
@Bean
@InboundChannelAdapter(channel = "marketingCategoryPoller", poller = @Poller(fixedDelay = "15000"))
public MessageSource<String> marketingCategoryPollerMessageSource() { return () -> makeTriggeringMessage(1);}

//A factory for producing messages which trigger the gateway
private Message<String> makeTriggeringMessage(int page) {
    //make a message for triggering marketingCategoryOutboundGateway
    return MessageBuilder.withPayload("")
            .setHeader("Host", "eclinic")
            .setHeader("page", page)
            .build();
}

//An outbound gateway, makes a request to the REST service and returns the response to marketingCategory channel
@Bean
@ServiceActivator(inputChannel = "marketingCategoryPoller")
public MessageHandler marketingCategoryOutboundGateway(@Qualifier("marketingCategory") MessageChannel channel) {
    //make a request to the REST service and push the response to the marketingCategory channel
}

//handler for REST service responses
@Bean
@ServiceActivator(inputChannel = "marketingCategory")
public MessageHandler marketingCategoryHandler() {
    return (msg) -> {
        //process the categories returned by marketingCategoryOutboundGateway
    };
}

enter image description here

2 个答案:

答案 0 :(得分:2)

我认为scale_x_yearmon是用于xy图的,因为它调用scale_x_continuous,但是我们可以像这样自己调用scale_x_continuous(仅更改标记为##的行):

ggplot(df, aes(x = dates, y = values)) + 
 geom_bar(position="dodge", stat="identity") +      
 theme_light() +
 xlab('Month') +
 ylab('values')+ 
 scale_x_continuous(breaks=as.numeric(df$dates), labels=format(df$dates,"%Y %m")) ##

screenshot

答案 1 :(得分:0)

我认为绘制zoo对象是一个问题。使用标准的Date类,并在ggplot中指定日期标签。您需要将日期添加到dates列的字符串中。然后,您可以使用scale_x_date并指定date_labels

library(tidyverse)
df <-  data.frame(dates = c("2019-01", "2019-02", "2018-08", "2018-09", "2018-10", "2018-11", "2018-12"), values= c(0,1,2,3,4,5,6)) %>% 
  arrange(dates) %>% 
  mutate(dates = as.Date(paste0(dates, "-01")))


ggplot(df, aes(x = dates, y = values)) + 
geom_bar(position="dodge", stat="identity") +
scale_x_date(date_breaks="1 month", date_labels="%Y %m") +
theme_light() +
xlab('Month') +
ylab('values')

result plot