How to eliminate the through-line from a legend element in R using ggplot

by Daniel Patterson   Last Updated December 26, 2017 21:26 PM

I'm having trouble eliminating a black through-line from an element in my legend. The black line is in the "% of Hires by Casual Users" element.

Below is my code, followed by a link to the output plot

EDIT - please note that I've added code to reproduce the problem elsewhere. This data is random and the output will not look the same as the visual below. However, it returns the same problem and can be used with the original code.

Account.type <- c("Casual", "Member", "Casual", "Member", "Casual", "Member", "Casual", "Member", "Casual", "Member")
how <- c(0, 10, 25, 35, 50, 60, 75, 100, 125, 150)
hire <- c(4540, 6780, 9125, 1000, 6993, 5435, 2347, 0693, 5434, 5432)
cas_percent <- c(34, 65, 54, 12, 65, 78, 89, 76, 54, 43)
plot_data <- data.frame(Account.type, how, hire, cas_percent)


    #plot x (time)
    plot <- ggplot(data = plot_data,
                   aes(x = how)) 

    #plot percent casuals
    plot <- plot + geom_ribbon(aes(ymin = 0, ymax = (cas_percent), fill = "% of Hires by Casual Users"), colour = "transparent", alpha = .5, show.legend = TRUE) 

    #plot hires 
    plot <- plot + geom_line(aes(y = hire/100, colour = Account.type), size = .8, show.legend = T)

    #fill aes 
    plot <- plot +   scale_fill_manual(name = '',  values=c("% of Hires by Casual Users" = "grey")) 

    #visualise
    plot

    #add title
    plot <- plot + labs(
      title = "Who Uses the Twin City Bike Share?", 
      y = "Hires (100's)",
      x = "Day of Week")

    #adjust x axis 
    plot <- plot + scale_x_continuous(
      breaks = c(0, 24, 48, 72, 96, 120, 144),
      label = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")) + 
      theme(axis.text.x = element_text(hjust=-0.05))

    #adjust right y axis
    plot <- plot + scale_y_continuous(sec.axis = sec_axis(~.*1, name = "Percent of Hires by Casual Users [%]"))

    #visualise
    plot

Output: enter image description here

Any suggestions on how I fix the legend?

Tags : r ggplot2


Answers 1


Without having a reproducible data it's just a blind guess, but I think you need to override aes for geom_ribbon. You will keep ribon color in your plot, but remove it from the legend.

Please try this:

# Adjusted for code provided by OP
plot +
    guides(color = guide_legend(override.aes = list(color = NA)))
PoGibas
PoGibas
December 26, 2017 21:03 PM

Related Questions


R - How to find points within specific Contour

Updated May 28, 2015 23:11 PM

How to see the code of a stored plot (ggplot)

Updated May 29, 2015 01:11 AM

R ggplot remove certain items from legend

Updated April 03, 2015 23:11 PM

add second axis label

Updated April 10, 2015 23:11 PM

Error in facet_grid in ggplot2

Updated October 09, 2016 09:11 AM