Search code examples
rplot

How to place the legend of a plot above of it in R


I have written the following code:

#data
tot_profit_without = c(5.67856,5.19891,5.6146,5.91454,5.10273,5.13607,4.7871,4.96507,4.43748,4.02154,3.21159,2.97219,2.27968,2.06904,1.95625,1.86762,1.25334,1.30521,0.65476,0.79812,0.91899)

tot_profit_with = c(2*10^(-7),8*10^(-7),4.5*10^(-6),2.08*10^(-5),5.81*10^(-5),0.000201,0.000436,0.001166,0.00218,0.003718,0.004665,0.007423,0.008421,0.011651,0.015575,0.021022,0.044973,0.385499,0.358526,0.608648,0.790532)

app2 = data.frame(tot_profit_without,tot_profit_with)

#Let's plot
plot(x = c(seq(0.0001,0.0016,by = 0.0001),seq(0.002,0.006,by = 0.001)),y = app2$tot_profit_without, type = "l", ylim = c(0,6), xaxt = "n", yaxt = "n", xlab = "k", ylab = "Profit",lwd = 2)
axis(2, at = seq(0,6,by = 1),las = 2)
axis(1, at = seq(0, 0.006, by = 0.001))

lines(c(seq(0.0001,0.0016,by = 0.0001),seq(0.002,0.006,by = 0.001)), app2$tot_profit_with, col = "black",lty = 2, lwd = 2)

abline(h = 1, lty = "9222", col = "black", lwd = 2) # lty = 6

legend("topleft", legend = c("without transaction costs taken into considetation", "with transaction costs taken into consideration"),
   col = c("black", "black"), lty = c(1, 2),
   lwd = 2, y.intersp = 0.11, horiz = FALSE, text.height = 0.8,
   inset = c(0, -0.3), xpd = TRUE, x.intersp = 0.5,
   seg.len = 0.5, text.width = 5,xjust = "left", yjust = 0.5,cex = 0.5)

and I get this, but I want to get this result. I have been searching for hours and I haven't found something yet. Can someone tell me what I should change in order to get the result I want?


Solution

  • You could do the whole thing in ggplot I guess:

    library(tidyverse)
    
    app2 %>%
      mutate(k = c(seq(0.0001, 0.0016, 0.0001), seq(0.002,0.006, 0.001))) %>%
      pivot_longer(-k, values_to = 'Profit') %>%
      ggplot(aes(k, Profit, linetype = name)) +
      geom_line() +
      geom_hline(yintercept = 1, lty = "9222", linewidth = 0.8) +
      scale_linetype_manual(NULL, values = c(2,1),
                  labels = c("with transaction costs taken into consideration", 
                             "without transaction costs taken into consideration")) +
      scale_x_continuous(breaks = 0:6*1e-3) +
      scale_y_continuous(breaks = 0:6) +
      theme_classic(base_size = 16) +
      theme(legend.position = 'top',
            legend.direction = 'vertical',
            legend.background = element_rect(fill = 'white', color = 'black'),
            axis.ticks.length = unit(3, 'mm'),
            axis.line = element_blank(),
            panel.border = element_rect(fill = NA, color = 'black', linewidth = 1))
    

    enter image description here