Home > Software design >  Creating a simple Graph in R
Creating a simple Graph in R

Time:10-02

how can I create this in R?:

enter image description here

I can't seem to get the data.frame right in order to display the variables correctly.

CodePudding user response:

Something like this?

df1 <- data.frame(x = rep(seq(0.95:1, by = 0.01), 2), cat = "A")
df1 <- df1[order(df1$x), ]
y <- c(rep(seq(0, 1, by = 1/6), 2))
df1$y <- sort(y)[2:13]
df2 <- data.frame(x = c(0, 1, 1, 1.5), y = c(0, 0, 1, 1), cat = "B")

df <- rbind(df1, df2)

library(ggplot2)

ggplot(df, aes(x, y, colour = cat))  
  geom_path()  
  coord_cartesian(xlim = c(0.95, 1))  
  scale_y_continuous(breaks = seq(0, 1, by = 0.2))

enter image description here

CodePudding user response:

It can be crated step by step with "base R" functions. It can be done with data frames, but simple vectors will also do here.

  • create data sets for A and B
  • plot both with steps type="s"
  • optionally: suppress default axes and make your own, with labels from 0.95 to 1.00 only
  • add a legend
  • optionally: add the two hand-drawn red points
x  <- seq(0.94, 1.0, 0.01)
A  <- seq(0, 1, length.out = length(x))

x2 <- c(0.94, 1, 1.01)
B  <- c(0,    1, 1)

plot(x, A, type = "s", xlim = c(0.94, 1.01), ylab = "F(x)", axes = FALSE)
lines(x2, B, type = "s", col = "blue")

axis(1, at=pretty(c(0.95, 1)))
axis(2)
box()

legend("topleft", lty=1, 
       legend = c("Lotterie A", "Lotterie B"), 
       col = c("black", "blue"))

points(c(1, 1), c(0, 1), col = "red")

plotted output

  • Related