我有一个数据框来绘制 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()
答案 0 :(得分:1)
在我看来,您的函数仅应用于列的第一行。该值被复制。使用 lapply
返回所有唯一值。但是,如果不将其设为数字(并对其进行排序),我不知道在此示例中是否有意义,因此您可能还想添加它。
ggplot(iris, aes(x = Species, y = trial, color = Species)) +
geom_point() +
scale_y_discrete(labels = lapply(iris$trial, myfun)) +
theme_bw()
答案 1 :(得分:0)
您可以使用正则表达式来提取所需的值。
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)
。