How to write point values to a lineplot in R?

Viewed 73

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$A, type = "o", pch = 20)**

Sorry, I made an edit to make my question clearer. Here below is the example plot for 10 random numbers enter image description here

3 Answers

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

Plot lines, then add text:

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

#base plot
plot(x$A, type = "o", pch = 20, ylim = range(x$A * 1.3))
text(x = seq_along(x$A), y = x$A + 0.3, 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(cbind(x = seq_along(x$A), x),
       aes(x = x, y = A, label = round(A, 2))) +
  geom_line() +
  geom_point() +
  geom_label_repel()
  #geom_text_repel()

enter image description here

You could make a base R "type b" equivalent.

The OP hasn't specified that every y value should be set to zero.

library(ggh4x)
#> Loading required package: ggplot2

set.seed(1)
x = data.frame(A = rnorm(10)) 

ggplot(x, aes(1:10, A)) +
  geom_pointpath(shape = NA) +
  geom_text(aes(label = round(A,2))) +
  labs(x= "Index")

Created on 2022-05-27 by the reprex package (v2.0.1)

Related