时间序列数据为月度时如何均匀间隔geom_bar

leb*_*noz 5 r ggplot2

我有一个df日期和权重的数据框(dput下面的语句),其中日期是当月的最后一个工作日:

   date    factor    weight
---------------------------
2011-12-30 Margin   0.1833979
2011-12-30    ROE   0.4116400
2012-01-31 Margin   0.1268960
2012-01-31    ROE   0.5407965
2012-02-29 Margin   0.1203718
2012-02-29    ROE   0.5175672
...
Run Code Online (Sandbox Code Playgroud)

当我尝试制作条形图时,条形之间的空间不均匀并且看起来很糟糕:

library(ggplot2)
ggplot(df, aes(x = date, y = weight, fill = factor)) + geom_col(colour = "black")
Run Code Online (Sandbox Code Playgroud)

我的图表

ggplot2使条形分布看起来均匀的最简单方法是什么?

我的dput声明:

df = structure(list(date = structure(c(15338, 15338, 15370, 15370, 15399, 15399, 15429, 15429, 15460, 15460, 15491, 15491, 15520, 15520, 15552, 15552, 15583, 15583, 15611, 15611, 15644, 15644, 15674, 15674), class = "Date"), 
  factor = c("Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE", "Margin", "ROE"), 
  weight = c(0.183397892362647, 0.411640022340554, 0.126896048517931, 0.540796526250458, 0.120371806492843, 0.517567227285325, 0.12565548480002, 0.468107694641952, 0.128735747553961, 0.491574638977635, 0.307725896135512, 0.310517566155656, 0.340289734678739, 0.294489504073278, 0.294029009420599, 0.343346263176468, 0.311122787549636, 0.289283606959861, 0.252528512248826, 0.343976191871968, 0.325326565998995, 0.403795335070129, 0.331246359784484, 0.429392163631535)), 
  class = "data.frame", 
  .Names = c("date", "factor", "weight"), row.names = c(NA, -24L))
Run Code Online (Sandbox Code Playgroud)

eip*_*i10 3

您可以将所有日期值转换为月年因子。例如:

library(tidyverse)
library(lubridate)

# Add month-year factor variable based on date
df = df %>% mutate(month = paste(month(date, label=TRUE), year(date)),
                   month = factor(month, levels=unique(month)))

# Label every third month
labs = unique(as.character(df$month))
labs[grep(paste(month.abb[-seq(1,12,3)], collapse="|"), labs)] = ""

ggplot(df, aes(x = month, y = weight, fill=factor)) + 
  geom_col(colour = "black") +
  scale_x_discrete(labels=labs) +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述