我有一个日期和权重的数据框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
...
当我尝试做条形图时,条形图之间的空格不均匀且看起来很糟糕:
library(ggplot2)
ggplot(df, aes(x = date, y = weight, fill = factor)) + geom_col(colour = "black")
使条形图分布看起来一致的最简单的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))
答案 0 :(得分: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()