geom_line(data = df1, aes(x1, y1), color = "darkblue") + geom_line(data = df2, aes(x2, y2), linetype = "dashed")ggplot allows us to make multiple calls to different geom_ functions, each with its own data source, if desired. Then ggplot will look at all the data we are plotting and adjust the ranges to accommodate all the data. The graph with expanded limits is shown in Figure 10-38. rcbk 1038 Figure 10-38. Two lines, one plot 10.16 Adding Vertical or Horizontal Lines Problem You want to add a vertical or horizontal line to your plot, such as an axis through the origin or a pointer to a threshold. Solution The ggplot functions geom_vline and geom_hline produce vertical and horizontal lines, respectively. The functions can also take color, linetype, and size parameters to set the line style:
- using the data.frame df1 from the prior recipe
aes(x = x1, y = y1) + geom_point() + geom_vline( xintercept = 10, color = "red", linetype = "dashed", size = 1.5 ) + geom_hline(yintercept = 0, color = "blue")Figure 10-39 shows the resulting plot with added horizontal and vertical lines. rcbk 1039 Figure 10-39. Vertical and horizontal lines Discussion A typical use of lines would be drawing regularly spaced lines. Suppose we have a sample of points, samp. First, we plot them with a solid line through the mean. Then we calculate and draw dotted lines at ±1 and ±2 standard deviations away from the mean. We can add the lines into our plot with geom_hline: samp ← rnorm(1000) samp_df ← data.frame(samp, x = 1:length(samp