如何解决如何更改ggplot中变量的显示名称?
我正在寻找一种方法来更改ggplot2
中变量的显示名称,而无需注意使用该变量的位置。我最好用代码说明我的问题:
library(ggplot2)
# this works,plotting hwy over year
print(ggplot(mpg,aes(x = year,y = hwy)) + geom_point())
# now I want to show hwy as High way$,so I need to check where I use hwy,# find the corresponding label/guide/...,and change that:
print(ggplot(mpg,y = hwy)) + geom_point() + labs(y = "Hi way$"))
# now I want to plot cty instead of hwy - that's easy to do:
print(ggplot(mpg,y = cty)) + geom_point() + labs(y = "Hi way$"))
# oops,I forgot to change the label! that's bad!
# what I would like is to avoid mistakes like this by being able to change default
# labels based on the original variable,not based on the aesthetics to which this
# variable is assigned.
# this way,I could change y = hwy to y = cty in aes,but hwy = "Hi way$" would
# not lead to an incorrect labeling if forgotten:
print(ggplot(mpg,y = hwy)) + geom_point() + ren(hwy = "Hi way$"))
这是否存在?如果没有,这将是有价值的补充吗?请注意,显示名称可能不是在代码中使用的好标识符,因此我要避免更改原始数据帧的colnames
。
解决方法
我从来没有遇到过这个问题,因为当我关心漂亮的标签时,无论如何情节都是经过精心优化和独特的。
我建议这种方法:
library(ggplot2)
my_var <- "hwy"
my_lab <- "Hi way$"
print(ggplot(mpg,aes_string(x = "year",y = my_var)) +
geom_point() + labs(y = my_lab))
,
以下是基于@stefan的comment的答案:
library(ggplot2)
Hmisc::label(mpg$hwy) <- "Hi way$"
print(ggplot(mpg,aes(x = year,y = hwy)) + geom_point() + ggeasy::easy_labs())
这是它发出警告的缺点
不知道如何为带标签/整数类型的对象自动选择比例。默认为连续。
这是因为标记mpg$hwy
会将列从原始类型(例如"integer"
)转换为c("labelled","integer")
,并且ggplot的所有组件似乎都不知道该怎么做。无论如何,在定义比例的更复杂的图中这可能不是问题,但是我可能会为此向ggplot
提出问题。
编辑:此功能也适用:
library(ggplot2)
attr(mpg$hwy,"label") <- "Hi way$"
print(ggplot(mpg,y = hwy)) + geom_point() + ggeasy::easy_labs())
可爱!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。