R:在系数路径图

时间:2018-04-01 20:37:15

标签: r ggplot2

我有这个非常简单的代码,可以生成系数路径图:

library(ggplot2)
library(dplyr)
library(tidyr)
value2=matrix(c(0,0,2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,2,3,4,0,0,0,0,0), nrow =5 )
#Plot
L1 <- function(x) sum(abs(x));
bind_cols(
  as.data.frame(value2) %>%
    summarise_all(funs(L1(.))) %>%
    t() %>%
    as.data.frame() %>%
    rename(x = V1),
  t(value2) %>%
    as.data.frame() %>%
    rename_all(funs(gsub("V", "", .)))) %>%
  gather(row, y, 2:(nrow(value2)+1)) %>%
  ggplot(aes(x, y, colour = row)) + geom_line() +
  geom_vline(xintercept = 4.5 , col = "black")

这是它产生的情节: enter image description here 我想要做的只是在行的末尾添加标签,对于黑线我也想添加它的值。 像这样:

enter image description here

我可以使用任何ggplot函数吗?

1 个答案:

答案 0 :(得分:1)

ggrepel可以做这种工作

library(ggplot2)
library(dplyr)
library(tidyr)
library(ggrepel)

value2 = matrix(c(0,0,2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,2,3,4,0,0,0,0,0), nrow=5)

#Plot
L1 <- function(x) sum(abs(x));

bind_cols(
  as.data.frame(value2) %>%
    summarise_all(funs(L1(.))) %>%
    t() %>%
    as.data.frame() %>%
    rename(x = V1),
  t(value2) %>%
    as.data.frame() %>%
    rename_all(funs(gsub("V", "", .)))) %>%
  gather(row, y, 2:(nrow(value2)+1)) -> df

ggplot(df, aes(x, y, colour = row)) + geom_line() +
  geom_vline(xintercept = 4.5 , col = "black") + 
  geom_text_repel(
    data = subset(df, x == max(x)),
    aes(label = row),
    size = 6,
    nudge_x = 1,
    segment.color = NA
  ) +
  theme_classic() +
  theme(legend.position = "none")

reprex package(v0.2.0)创建于2018-04-01。