1
votes

I would like to use the labeller argument (and function) in facet_grid from the ggplot2 package, so that multiple labels on one axis go under each other, rather than next to each other.

In the reproducible example below, I would like to get the label to say the company name with the sector underneath it in the same 'label box' i.e. 'ABC Ltd\nAAAAAAAA' and 'DEF plc\nAAAAAAAA' and 'GHI LLP\nBBBBBBBBB' for the y axis facet labels. Ideally I would like to extend this for multiple additional label descriptions that go underneath.

require(ggplot2)
require(reshape2)
require(dplyr)

dat <- data.frame(date=Sys.Date()+seq(1000),
                  stock_px_1=100*cumprod(c(1,1+rnorm(999,0.00003,0.0004))),
                  stock_px_2=500*cumprod(c(1,1+rnorm(999,0.00001,0.0003))),
                  stock_px_3=10*cumprod(c(1,1+rnorm(999,0.00005,0.0005))))

stock_info <- data.frame(px_name=paste0('stock_px_',seq(3)),
                         stock_id=c('a1b2c3','d4e5f6','g7h8i9'),
                         sector=c('AAAAAAAA','AAAAAAAA','BBBBBBBBB'),
                         long_name=c('ABC Ltd','DEF plc','GHI LLP'))


dat_melted <- melt(dat,id.vars='date',variable.name='px_name',value.name='price')

joined_dat <- left_join(dat_melted,stock_info,by='px_name')

ggplot(joined_dat,aes(x=date,y=price,color=px_name))+
  geom_path()+
  facet_grid(long_name+sector~.,scales='free_y')+
  theme(strip.text.y=element_text(angle=0))+
  theme(legend.position='none')
2

2 Answers

1
votes

One way could be to simply add a new column that holds the combined labels:

joined_dat$combinedlabel=paste0(joined_dat$long_name,"\n",joined_dat$sector)

And then use said column to facet:

ggplot(joined_dat,aes(x=date,y=price,color=px_name))+
  geom_path()+
  facet_grid(combinedlabel~.,scales='free_y')+
  theme(strip.text.y=element_text(angle=0))+
  theme(legend.position='none')
1
votes

You can use the label_wrap_gen option as follows

p <- sample_data %>%  ggplot(aes(x= Data, fill=Category)) + geom_density() + 
facet_grid(Name~Category, labeller = label_wrap_gen(width=10)) +
xlab("Data (Unit)")