Search code examples
rggplot2geom-barstacked-chart

Stacked Barplot with well placed Dates on x-Axis


I am trying to build a stacked Barplot, without gaps between the bars and Dates on the x-Axis. To achieve this, I set the width to the difference between the following dates and nudget the x position by half the datedifference. So if the Date is 2018-01-31, I want the bar to start exactly at that date and end at the next date (2018-02-28). So far that works well, but when introducing that positioning logic, my bars stopped being stacked (picture: bars are overlapping but not stacked -> would sum up to 1). How can I restack them?enter image description here

ggplot(weights_gg2, aes(x=Date, y=Exposure, fill=Bond)) +
  geom_bar(stat="identity", colour="white", width=rep(c(diff(weights_df$Date), 20), 13), position = position_nudge(x=rep(c(diff(weights_df$Date), 20), 13)/2)) +
  theme_bw(base_size=12)

Needed data: weights_df contains all data and the dates, while weights_gg2 is already melted for ggplot


Solution

  • darios answer was the most accurate to the problem:

    Manipulate input data rather than changing the position afterwards:

    hjust <- rep(c(diff(weights_df$Date), 20), 13)/2
    ggplot(weights_gg2, aes(x=Date+hjust, y=Exposure, fill=Bond)) +
      geom_bar(stat="identity", colour="white", width=rep(c(diff(weights_df$Date), 20), 13))+
      theme_bw(base_size=12)