首页 > 解决方案 > Adding a line to a blank R Plot

问题描述

So I have the following code that produced a blank canvas:

plot(1, type="n", xlab="Output", ylab="Real Interest Rate", xlim=c(9800, 10400), ylim=c(0.01, 0.07))

Now I am wondering how to get a line on the graph intersecting points (10000, 0.05) and (10200, 0.03).

I only want the line on my plot.

Any help is greatly appreciated!

标签: rggplot2plot

解决方案


Base R - use the lines() function.

x <- c(10000, 10200)
y <- c(0.05, 0.03)
plot(1, 
     type="n", 
     xlab="Output", 
     ylab="Real Interest Rate", 
     xlim=c(9800, 10400), 
     ylim=c(0.01, 0.07))
lines(x, y)

enter image description here

In ggplot2, use geom_line().

library(ggplot2)
x <- c(10000, 10200)
y <- c(0.05, 0.03)
ggplot(data.frame(x, y), aes(x, y)) + 
  geom_line() +
  scale_x_continuous(name = "Output", 
                     limits = c(9800, 10400), 
                     breaks = seq(9800, 10400, 100) +
  scale_y_continuous(name = "Real Interest Rate", 
                     limits = c(0.01, 0.07), 
                     breaks = seq(0.01, 0.07, 0.02)) +
  theme_bw()

enter image description here


推荐阅读