facet_grid labeller两行 [英] facet_grid labeller two lines

查看:68
本文介绍了facet_grid labeller两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 ggplot2 包的 facet_grid 中使用 labeller 参数(和函数),以便在一个轴上使用多个标签互相靠近,而不是互相靠近.

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.

在下面的可复制示例中,我想让标签在同一标签框"中说出公司名称及其下方的部门.y轴刻面标签为'ABC Ltd \ nAAAAAAAA'和'DEF plc \ nAAAAAAAA'和'GHI LLP \ nBBBBBBBBBBB'.理想情况下,我想将此扩展为下面的多个其他标签描述.

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')

推荐答案

您可以按以下方式使用 label_wrap_gen 选项

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)") 

这篇关于facet_grid labeller两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆