0

I have a dataset like:

Date Value Label

2016/01 2 A

2016/02 3 A

2016/03 4 A

2016/04 5 A

2016/05 4 A

2016/05 4 B

2016/06 5 B

2016/07 6 B

The date "2016/05" appears two times in my dataset. I want to use ggplot2 to generate bar plot. How to make the bar plot have two same tick labels?

The target figure is like this: Sample Image

aosmith
  • 34,856
  • 9
  • 84
  • 118
cindy
  • 19
  • 2
  • Possible duplicate: https://stackoverflow.com/questions/18165863/multirow-axis-labels-with-nested-grouping-variables – aosmith Jul 20 '18 at 13:18

1 Answers1

1

One option is to create a new ID column so that you have unique categories on the x-axis:

library(tidyverse)

df <- structure(list(Date = c("2016/01", "2016/02", "2016/03", "2016/04", 
                              "2016/05", "2016/05", "2016/06", "2016/07"), 
                     Value = c(2L, 3L,4L, 5L, 4L, 4L, 5L, 6L), 
                     Label = c("A", "A", "A", "A", "A", "B", "B", "B")), .Names = c("Date", "Value", "Label"), 
                row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))

df %>%
  unite(ID, Date, Label) %>% 
  ggplot(aes(ID, Value)) +
  geom_col()

enter image description here

Alternatively you could use the Label column to facet the data like so:

df %>% 
  ggplot(aes(Date, Value)) +
  geom_col() +
  facet_wrap(.~Label, scales = "free_x")

enter image description here

G_T
  • 1,555
  • 1
  • 18
  • 34
  • Thanks for your answer! I prefer the second plot. However, when I run the code, there is an error! – cindy Jul 24 '18 at 08:44
  • df <- structure(list(Date = c("2016/01", "2016/02", "2016/03", "2016/04", "2016/05", "2016/05", "2016/06", "2016/07"), Value = c(2L, 3L,4L, 5L, 4L, 4L, 5L, 6L), Label = c("A", "A", "A", "A", "A", "B", "B", "B")), .Names = c("Date", "Value", "Label"), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame")) library(tidyverse) df %>% ggplot(aes(Date, Value)) + geom_col() + facet_wrap(.~Label, scales = "free_x") – cindy Jul 24 '18 at 08:45
  • ERROR while rich displaying an object: Error in combine_vars(data, params$plot_env, vars, drop = params$drop): At least one layer must contain all variables used for facetting – cindy Jul 24 '18 at 08:45
  • The code works fine for me. Try removing the period from the facet argument `facet_wrap(~Label, scales = "free_x")` – G_T Jul 25 '18 at 03:08