Home > other >  How to write point values to a lineplot in R?
How to write point values to a lineplot in R?

Time:05-26

I have a dataframe of single column with multiple values. I was using basic rplot function like plot() and points(). I successfully plotted the lineplot but I was unable to write point values from the dataframe onto the plot field. Is there anyway to add data values onto the plot?

Below is the following code for test

> x = data.frame(A = rnorm(10)) 
> plot(x, type = "o", pch = 20)

CodePudding user response:

Probably this is more than what you are asking, but you can add labels to the values you have in your line plot using ggplot:

library(ggplot2)

x = data.frame(A = rnorm(10),
               pos = runif(10, 0.1, 0.7))

ggplot(x)  
  
  geom_point(aes(x = A),
             y = 0)  
  
  geom_line(aes(x = A),
            y = 0)  
  
  geom_segment(aes(x = A,
                   xend = A,
                   y = 0,
                   yend = pos), 
               linetype = 2)  
  
  geom_label(aes(x = A,
                 y = pos,
                 label = round(A, 2)),
             size = 3)  

  scale_y_continuous(name = "",
                     limits = c(0, 0.8))   
  
  guides(y = "none")  
  
  theme_bw()

enter image description here

CodePudding user response:

Set y to zero, then use text after plot:

#data
set.seed(1); x = data.frame(A = rnorm(10), y = 0) 

#base plot
plot(x, type = "o", pch = 20, ylim = c(0, 1))
text(x = x$A, y = 0.2, labels = round(x$A, 2), srt = 90)

enter image description here

Or using ggplot with ggrepel for pretty labels:

#ggplot
library(ggplot2)
library(ggrepel) # pretty labels, avoid overlap:

ggplot(x, aes(A, y, label = round(A, 2)))  
  geom_point()  
  geom_label_repel()
  #geom_text_repel()

enter image description here

  • Related