在ggplot2 facet标签中表达 [英] Expression in ggplot2 facet labels

查看:207
本文介绍了在ggplot2 facet标签中表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在 ggplot2 facet标签中包含R 表达式



假设我正在绘制提示 data.frame

  library(reshape2)
>头(提示)
total_bill提示性吸烟者日时间大小
1 16.99 1.01女性无阳光晚餐2
2 10.34 1.66男性无阳光晚餐3
3 21.01 3.50男性无阳光晚餐3
4 23.68 3.31男性无太阳晚餐2
5 24.59 3.61女性无太阳晚餐4
6 25.29 4.71男性无太阳晚餐4


如下:

  library(ggplot2)$ b $ (形状= 1)+ 
facet_wrap(〜sex,ncol = 1)b $ sp $ ggplot(tips,aes(x = total_bill,y = tip / total_bill))+



我不希望将女性和男性作为小平面标签,而是希望拥有:
女性科目和男性科目,分别。据我所知,R中的标签是通过表达式函数实现的,但我不知道如何将它与 facet_wrap

解决方案

看起来过于复杂,但有效。您必须使用 facet_grid

  make_label<  - 函数(值){
x< - as.character(值)
bquote(斜体(。(x))〜科目)
}

plot_labeller< - 函数(变量,值){
do.call(表达式,lapply(levels(value),make_label))
}

ggplot(tips,aes(x = total_bill ,y = tip / total_bill))+
geom_point(shape = 1)+
facet_grid(。〜sex,labeller = plot_labeller)


I would like to have an R expression in a ggplot2 facet label.

Let's say I'm plotting the tips data.frame:

library(reshape2)
> head(tips)
  total_bill  tip    sex smoker day   time size
1      16.99 1.01 Female     No Sun Dinner    2
2      10.34 1.66   Male     No Sun Dinner    3
3      21.01 3.50   Male     No Sun Dinner    3
4      23.68 3.31   Male     No Sun Dinner    2
5      24.59 3.61 Female     No Sun Dinner    4
6      25.29 4.71   Male     No Sun Dinner    4

as follows:

library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + 
         geom_point(shape=1) + 
         facet_wrap(~sex, ncol = 1)

Instead of having "Female" and "Male" as facet labels I would like to have: "Female subjects" and "Male subjects", respectively. As far as I know italicizing a label in R is achieved through the expression function, but I don't know how to combine that with facet_wrap.

解决方案

Looks overly complicated, but works. You'll have to use facet_grid though.

make_label <- function(value) {
  x <- as.character(value)
  bquote(italic(.(x))~subjects)
}

plot_labeller <- function(variable, value) {
  do.call(expression, lapply(levels(value), make_label))
}

ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + 
  geom_point(shape=1) + 
  facet_grid(.~sex, labeller = plot_labeller)

这篇关于在ggplot2 facet标签中表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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