wligtenberg
wligtenberg

Reputation: 8025

How to show a hierarchical structure on the axis labels with ggplot2?

I would like to create a plot like this with ggplot2: Barplot with hierarchical labels on the x axis

(I made a small error here that caused not all labels to show up. obviously I do want all labels to show up :) ) However, my Google search didn't turn up anything. The closest I got was with barNest from plotrix, however, I don't like the quality of the graphs that are produced. The ggplot2 ones look a lot better.

In the ideal case, I would have expected to be able to do something like this: scale_x_discrete("Axis Title", labels=Level1+Level2+Level3) And then Level1, Level2 and Level3 would have been columns of the data frame that was used in the qplot function. If I can get this to work, I want to create a function to add this type of functionality to the scales function. Maybe scale_x_hierarchical would be better. Similar data can be generated with the following code:

data <- data.frame(
  Subject = c(rep(1, 48), rep(2, 48), rep(3, 48), rep(4, 48)), 
  month = rep(c(rep(1, 12), rep(4, 12), rep(7, 12), rep(10, 12)), 4), 
  day = rep(c(rep(1, 4), rep(11, 4), rep(21, 4)), 16), 
  hour = rep(c(0, 6, 12, 18), 48), 
  data = rnorm(192))

By the way, the image used here is created with Spotfire.

Upvotes: 8

Views: 2735

Answers (2)

aleoconn
aleoconn

Reputation: 79

It's quite difficult to understand what information you want to get out of this data presentation. Also please note that having a column called 'data' in an object called data is bad practice. I have renamed the column 'result'.

To achieve a similar effect with ggplot, you can use facet_wrap or facet_grid formatting properties to achieve a nested effect in general:

data %>% 
  mutate(date = map2(month, day, ~ymd(str_c("2023", .x, .y, sep = "-")))) %>% 
  unnest(date) %>% 
  ggplot()+
  geom_bar(aes(x = hour, y = result, 
               fill = as.factor(Subject)), 
           stat = "identity", position = "dodge")+
  labs(x = "Month/Day/Hour", fill = "Subject")+
  facet_wrap(~day(date)+format(date, "%B"), strip.position = "bottom",nrow = 1)+
  theme_bw()+
  theme(
    strip.placement = "outside",
    strip.background.x = element_blank(),
    strip.text.x = element_text(size = 8))

enter image description here

Here I've used facet_wrap and specified in the function that I want the labels at the bottom of the plot (strip.position = "bottom"). To more closely match the figure above, I've also specified that I want the facets to only plot in one row (nrow = 1).

The arguments in theme() control the placement of the facet strip text outside of the axis, the fill. and the text size.

Upvotes: 0

djq
djq

Reputation: 15286

It's a little different, but the LearnR blog has a post on linking a table to a graph so that it looks like this:

enter image description here

Upvotes: 0

Related Questions