在图的末尾添加值标签

时间:2018-06-11 15:20:36

标签: r ggplot2

我试图在情节中绘制标签。我做到了但他们并不是非常好。这是一个更好理解它的例子,我有这个情节: enter image description here

我想最后添加值,我这样做但是看起来很奇怪: enter image description here

有什么方法可以解决这个问题吗?我在代码末尾进行绘图,注释#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")

1 个答案:

答案 0 :(得分:2)

这里发生的主要事情是你在一个地方都有一堆文字标签,所以通过排斥它们并让它们将标签附加到它们的值上,你最终会在你的情节结束时出现这个星暴

要了解我的意思,请过滤数据以获取最大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值相关,因此轻推1当值只有0到0.6时,标签就会非常远。)我将分段颜色更改为中性,并在绘制分段之前调整最小距离。我添加了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(v0.2.0)创建于2018-06-11。