根据值替换轴标签
Replace axis labels according to their values
我正在使用 ggplot 绘制分组条形图。我想用唯一文本替换分组值,具体取决于它们的值。
但是我收到以下警告并且格式设置不符合我的要求。有条件地替换图中标签的修复方法是什么?
1: In if (x == "55") lab = "High" else if (x == "15") lab = "Low" :
the condition has length > 1 and only the first element will be used
LabelFormatter <- function (x) {
if (x == "55")
lab = "High"
else if (x == "15")
lab = "Low"
}
dF <- data.frame(name=rep(c("A","B","C"),2), value=sample(1:100,6), type=rep(c("15","55"),3))
p <- ggplot (dF, aes(x=type, y=value, fill=name)) + geom_bar(stat="identity", position="dodge")
p <- p + scale_x_discrete(label=LabelFormatter)
print(p)
你可以试试这个
p+scale_x_discrete(label= c("15"="low", "55"="high"))
Mamoun 是一个非常干净的解决方案,应该被接受为这个简单案例的答案。正如罗兰所说,您需要对格式化程序进行矢量化。这是一种方法,但不建议超过 2 ifelse
:
LabelFormatter <- function (x) {
ifelse(x=="55", "High",
ifelse(x=="15", "Low", x))
}
我正在使用 ggplot 绘制分组条形图。我想用唯一文本替换分组值,具体取决于它们的值。
但是我收到以下警告并且格式设置不符合我的要求。有条件地替换图中标签的修复方法是什么?
1: In if (x == "55") lab = "High" else if (x == "15") lab = "Low" : the condition has length > 1 and only the first element will be used
LabelFormatter <- function (x) {
if (x == "55")
lab = "High"
else if (x == "15")
lab = "Low"
}
dF <- data.frame(name=rep(c("A","B","C"),2), value=sample(1:100,6), type=rep(c("15","55"),3))
p <- ggplot (dF, aes(x=type, y=value, fill=name)) + geom_bar(stat="identity", position="dodge")
p <- p + scale_x_discrete(label=LabelFormatter)
print(p)
你可以试试这个
p+scale_x_discrete(label= c("15"="low", "55"="high"))
Mamoun 是一个非常干净的解决方案,应该被接受为这个简单案例的答案。正如罗兰所说,您需要对格式化程序进行矢量化。这是一种方法,但不建议超过 2 ifelse
:
LabelFormatter <- function (x) {
ifelse(x=="55", "High",
ifelse(x=="15", "Low", x))
}