从 data.frame 到 ggplot2 图例的表达式 [英] Expressions from data.frame to ggplot2 legend

查看:48
本文介绍了从 data.frame 到 ggplot2 图例的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不直接输入图例的情况下向图例条目添加表达式(因为我正在循环变量).基本上我想要这个:

I would like to add an expression to a legend entry without entering the legend directly (since I am looping over variables). Essentially I would like this:

d <- data.frame(x=1:10,y=1:10,f=rep(c("0–74",">=75"),each=5))
qplot(x,y,data=d,color=f)   

以这种方式输出:

qplot(x,y,data=d,color=f) +
scale_colour_manual(values=1:2,breaks=c("0–74",">=75"),
labels=c(expression(0<=75), expression("">=75)))

(但实际上我希望第一个条目 0<=74 为 0-74,但我在混合表达式和非表达式时遇到问题.)

(But actually I would like the the first entry 0<=74 to be 0-74, but I'm having trouble mixing expressions and non-expressions.)

我确定这是某种设置,但我尝试过的所有方法都没有奏效.有什么想法吗?

I'm sure it's some kind of setting, but everything I've tried hasn't worked. Any ideas?

推荐答案

我认为您可以在循环中使用 parse(text=) 将字符串转换为适当的表达式.因此,您可以通过从 f 变量中获取字符串并以如下方式传递它们(可能需要进行一些调整)来使用适当的标签设置 scale_colour_manual:

I think you can do this within your loop by using parse(text=) to convert a string to the appropriate expression. So you could set scale_colour_manual with the appropriate labels by taking the character strings from your f variable and passing them in a manner something like this (some tweaking may be necessary):

scale_colour_manual(...,labels=c(parse(text=lab1),parse(text=lab2)))

虽然 parse 不喜欢 ">=75",所以你可能需要类似 "''>=75" 的东西.

Although parse doesn't like ">=75" so you'll probably want something like "''>=75".

例如:

qplot(x,y,data=d,color=f) +
  scale_colour_manual(values=1:2,breaks=c("0–74",">=75"),
  labels=c(parse(text="0-74"), parse(text=paste("''",">=75",sep=""))))

这篇关于从 data.frame 到 ggplot2 图例的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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