如何更改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())

可爱!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...