Home > OS >  Multiple lines with data labels (R)
Multiple lines with data labels (R)

Time:06-24

I would like to plot multiple lines with data labels but all my attempts have returned an error message so far.

ggplot(data, aes(year))   
  geom_line(aes(y = var1), color = "#E20335", size = 1.5)  
  geom_point(aes(y = var1), color = "#E20335", size = 3)  
  geom_line(aes(y = var2), color = "#292753", size = 1.5)  
  geom_point(aes(y = var2), color = "#292753", size = 3)  
  scale_x_continuous(breaks = 2010:2020)  
  scale_y_comma()  
        labs(title = 'something',
         subtitle = 'something',
         x = 'This axis title intentionally left blank',
         y = 'This axis title intentionally left blank',
         caption = 'something')

I want to insert the labels into this code, so that they are placed around data points. Any help would be greatly appreciated.

CodePudding user response:

As suggested in the comment you can try with geom_label. However, it is better if you provide an example dataset such as an in-built dataset or the output of dput(data). Also, include the library you are working with to help people help you. Since you do not specify which variable do you want to label I post an example with the mtcars dataset

library(ggplot2)
library(hrbrthemes)
ggplot(mtcars, aes(mpg))   
  geom_line(aes(y = disp), color = "#E20335", size = 1.5)  
  geom_point(aes(y = disp), color = "#E20335", size = 3)  
  geom_line(aes(y = hp), color = "#292753", size = 1.5)  
  geom_point(aes(y = hp), color = "#292753", size = 3)  
  scale_x_continuous(breaks = 2010:2020)  
  scale_y_comma()  
  labs(title = 'something',
       subtitle = 'something',
       x = 'This axis title intentionally left blank',
       y = 'This axis title intentionally left blank',
       caption = 'something') 
  geom_label(aes(y=disp,label=carb)) 
  geom_label(aes(y=hp,label=carb))

For this kind of plot and data it is typically better to reshape the dataset to a long format so it is easier to manage legend, color and other ggplot optionsenter image description here

  • Related