2

I have this data frame to construct some lines chart using ggplot2. lb is what I want my label to be on x-axis while each other variables (x0.6, x0.8, x0.9, x0.95, x0.99, and x0.999) will be against lb on the y-axis.

# my data
lb <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
x0.6 <- c(0.9200795, 0.9315084, 0.9099002, 0.9160192, 0.9121120, 0.9134098, 0.9130619, 0.9128494, 0.9144164) 
x0.8 <- c(0.9804872, 1.0144678, 0.9856382, 0.9730490, 1.0032707, 1.0036311, 0.9726198, 0.9986403, 1.0022643) 
x0.9 <- c(1.055256, 1.016159, 1.067242, 1.089894, 1.043502, 1.041497, 1.037738, 1.023274, 1.040536) 
x0.95 <- c(1.058024, 1.105353, 1.069076, 1.061077, 1.095764, 1.096789, 1.096670, 1.121497, 1.109918)
x0.99 <- c(1.107258, 1.098061, 1.118248, 1.101253, 1.083208, 1.109715, 1.083704, 1.083704, 1.118057) 
x0.999 <- c(1.110732, 1.119625, 1.121221, 1.087423, 1.093228, 1.094003, 1.108910, 1.112413, 1.096734)

#my datafram
pos11 <- data.frame(lb, x0.6, x0.8, x0.9, x0.95, x0.99, x0.999)


#load packages
library("reshape2")
library("ggplot2")
# this `R` CODE reshapes the data
long_pos11 <- melt(pos11, id="lb")
# Here is the `R` code that produces the `line-chart`
pos_line <- ggplot(data = long_pos11,
   aes(x=AR, y=value, colour=variable)) +

geom_line()

I want the line-chart to show elements of the vector lb (1, 2, 3, 4, 5, 6, 7, 8, 9) on x-axis as its label just like date is 0n Plotting two variables as lines using ggplot2 on the same graph

Daniel James
  • 1,381
  • 1
  • 10
  • 28

2 Answers2

1

Try this. As your variable is of numeric type you would need to set it as factor and then also add group to your aes() statement. Here the code:

library("reshape2")
library("ggplot2")
# this `R` CODE reshapes the data
long_pos11 <- melt(pos11, id="lb")
# Here is the `R` code that produces the `line-chart`
pos_line <- ggplot(data = long_pos11,
       aes(x=factor(lb), y=value, colour=variable,group=variable)) +
  geom_line()+xlab('lb')

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
1

We can also use pivot_longer

library(ggplot2)
library(tidyr)
library(dplyr)
pos11 %>%
    pivot_longer(cols = -lb) %>%
    mutate(lb = factor(lb)) %>%
    ggplot(aes(x = lb, y = value, color = name, group = name)) +
      geom_line() +
      xlab('lb')
akrun
  • 874,273
  • 37
  • 540
  • 662