我正在尝试在图中绘制标签。我这样做了,但它们看起来不太好。这是一个更好理解的例子,我有这个情节:
有什么办法可以解决这个问题吗?我在代码末尾进行绘图,其中注释为#plotting
。
这是可重现的代码:
library(glmnet)
library(dplyr)
library(tidyr)
set.seed(100)
n=100
p=50
X=matrix(rnorm(n*p), nrow=n)
y=matrix(rnorm(n), nrow=n)
lam = seq(0.1,7,length.out=100)
lm=glmnet(X,y,alpha=1,lambda=lam, intercept=FALSE, standardize=FALSE)
value1=as.matrix(coef(lm))
#creating a dataframe
L1 <- function(x)
sum(abs(x))
bind_cols(
as.data.frame(value1) %>%
summarise_all(funs(L1(.))) %>%
t() %>%
as.data.frame() %>%
rename(x = V1),
t(value1) %>%
as.data.frame() %>%
rename_all(funs(gsub("V", "", .)))
) %>%
gather(row, y, 2:(nrow(value1) + 1)) -> dataf
#plotting
ggplot(dataf, aes(x, y, colour = row)) + geom_line() +
geom_text_repel(
data = subset(dataf, x == max(x)),
aes(label = row),
size = 2,
nudge_x = 1
) +
theme(legend.position = "none")
最佳答案
这里发生的主要事情是,你在一个地方有一堆文本标签,因此通过排斥它们并让它们有将标签附加到其值的片段,你最终会在绘图的末尾得到这个星爆.
要明白我的意思,请过滤数据以获得最大 x 值(这是您放置标签的位置)以及 y == 0 的行:其中有 35 个!因此,您有 35 位文本,它们都在争夺同一个位置,并且彼此排斥。
dataf %>%
filter(x == max(x), y == 0) %>%
nrow()
#> [1] 35
您可以看到这一点的第二种方法是设置将文本连接到其值的段的颜色。如果将其设置为灰色,则可以将这些线段与实际的 geom_line 区分开来,因为现在它们的颜色不同。
ggplot(dataf, aes(x, y, colour = row)) +
geom_line() +
geom_text_repel(
data = . %>% filter(x == max(x)),
aes(label = row),
size = 2,
nudge_x = 0.01,
segment.color = "gray60"
) +
scale_x_continuous(expand = expand_scale(mult = c(0.05, 0.1))) +
theme(legend.position = "none")
这里有几种方法可以避免这种困惑:我减少了 nudge_x
,这样文本就会更接近线条(nudge_x
与您的 x 值相关) ,因此当值仅为 0 到 0.6 左右时,微移 1 会使标签变得很远)。我将线段颜色更改为中性颜色,并在绘制线段之前调整了最小距离。我添加了一个 expand_scale
来在右侧留出更多空间(这仅在 ggplot 的开发版本中存在)。最重要的是,我取出了 0 值的标签。
您可能应该根据自己的喜好调整这些内容,但希望这是清理它的开始。
ggplot(dataf, aes(x, y, colour = row)) +
geom_line() +
geom_text_repel(
data = . %>% filter(x == max(x), y != 0),
aes(label = row),
size = 2,
nudge_x = 0.01,
min.segment.length = 5,
segment.color = "gray60"
) +
scale_x_continuous(expand = expand_scale(mult = c(0.05, 0.1))) +
theme(legend.position = "none")
由reprex package于2018年6月11日创建(v0.2.0)。
关于r - 在绘图末尾添加值标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50801097/