RNB
RNB

Reputation: 477

Second line in ggplot is not showing correct linetype and also not in legend

I recently had some code that produced exactly the ggplot in R that I was looking for. After updating my ggplot package recently, that code no longer works as I wanted. The new plot no longer shows the correct linetype for my horizontal line. Nor does the line show up in the legend. As I said, it used to work perfectly.

Here is a quick, reproducible example using the mtcars dataset (my real data cannot be shared):

    model <- lm(mtcars$wt ~ mtcars$hp)
    mtcars$pred <- predict(model, mtcars, level = 0)

    theme<-theme(axis.title.x = element_text(face="bold"),
         axis.text.x  = element_text(angle=90, face="bold", colour="black"),
         axis.title.y = element_text(face="bold", size=12),
         axis.text.y = element_text(angle=90, face="bold", colour="black"),
         plot.title = element_text(lineheight=.8, face="bold"),
         panel.grid.major = element_line(colour = 'black'),
         panel.grid.minor = element_line(colour = NA),
         panel.background = element_rect(fill = 'white'),
         strip.background = element_rect(fill = 'white'))

    plot<-ggplot(mtcars, aes(x = hp, y = pred)) +
      geom_point(aes(x=hp, y=wt, color = as.factor(am)), position=position_jitter(width=0.5,height=0.5), alpha = 0.5) +
      geom_hline(yintercept = 4.5, size = 1, aes(linetype = "y = 4.5")) +
      geom_line(aes(linetype= "Best fit"), size = 1) +
      scale_y_continuous(name= "Weight") +
      scale_color_manual('AM', values = c('orange', 'purple')) +
      scale_linetype_manual('Lines', values = c("Best fit" = 1, "y = 4.5" = 2)) +
      xlab("Hewlett Packard") +
      guides(linetype = guide_legend(keywidth = 2, keyheight = 1)) +
      theme

    plot

Here is the plot: enter image description here

The y=4.5 line should be dashed, but as you can see it is still solid. Furthermore, it is not showing in the legend. Another thing I noticed is that the legend titles formatting have changed. They used to be bold but are not anymore.

Can anyone help me to fix my code? Also can anyone explain why this changed?

Upvotes: 0

Views: 720

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98499

You should put yintercept = 4.5 inside the aes() of geom_hline() and then legend and corect linetype will be used.

  +geom_hline( size = 1, aes(yintercept = 4.5,linetype = "y = 4.5"))

Upvotes: 2

Related Questions