R: plotting values at the end of the lines in a co

2019-07-26 08:17发布

问题:

This question already has an answer here:

  • Plot labels at ends of lines 5 answers

I have this very simple code that generates a coefficient path plot:

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")

And here is the plot it generates: What I want to do is just add the labels at the end of the line, and for the black line I want to add its value too. Like this:

Is there any ggplot function that I could use for this?

回答1:

ggrepel can do this kind of job

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")

Created on 2018-04-01 by the reprex package (v0.2.0).



标签: r ggplot2