ggplot 如何在 R 中编辑轴标签
ggplot how to edit axis labels in R
我有一个要绘制的数据框,其中 y_axis 变量是一个字符。我只想将字符的最后一部分与 '_'
作为分隔符。
这里是 iris
数据集的示例。如您所见,所有 y_axis
标签都是相同的。我该怎么做?谢谢
iris$trial = paste('hello', 'good_bye', iris$Sepal.Length, sep = '_')
myfun = function(x) {
tail(unlist(strsplit(x, '_')), n = 1)
}
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = function(x) myfun(x)) +
theme_bw()
在我看来,您的功能仅适用于该列的第一行。该值被复制。使用 lapply
returns 所有唯一值。但是,如果不将其设为数字(并对其进行排序),我不知道在这个示例中是否有意义,因此您可能也想添加它。
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = lapply(iris$trial, myfun)) +
theme_bw()
您可以改用正则表达式来提取所需的值。
library(ggplot2)
#This removes everything until the last underscore
myfun = function(x) sub('.*_', '', x)
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = myfun) +
theme_bw()
如果你想从y轴值中提取数字,你也可以使用scale_y_discrete(labels = readr::parse_number)
。
我有一个要绘制的数据框,其中 y_axis 变量是一个字符。我只想将字符的最后一部分与 '_'
作为分隔符。
这里是 iris
数据集的示例。如您所见,所有 y_axis
标签都是相同的。我该怎么做?谢谢
iris$trial = paste('hello', 'good_bye', iris$Sepal.Length, sep = '_')
myfun = function(x) {
tail(unlist(strsplit(x, '_')), n = 1)
}
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = function(x) myfun(x)) +
theme_bw()
在我看来,您的功能仅适用于该列的第一行。该值被复制。使用 lapply
returns 所有唯一值。但是,如果不将其设为数字(并对其进行排序),我不知道在这个示例中是否有意义,因此您可能也想添加它。
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = lapply(iris$trial, myfun)) +
theme_bw()
您可以改用正则表达式来提取所需的值。
library(ggplot2)
#This removes everything until the last underscore
myfun = function(x) sub('.*_', '', x)
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = myfun) +
theme_bw()
如果你想从y轴值中提取数字,你也可以使用scale_y_discrete(labels = readr::parse_number)
。