Show legend in double line graphic

Hello. I'm doing a double y axe line graphic, but ggplot doesn't show legend.

Here is the dataframe:

asis  <- data.frame(
  stringsAsFactors = FALSE,
               Jor = c(2L, 4L, 5L, 7L, 9L, 11L, 14L, 16L, 18L),
            Asist1 = c(5643L,7152L,5650L,5749L,
                       5128L,5815L,5149L,6258L,4645L),
              City = c("Ibiza","Barcelona",
                       "Zaragoza","Tenerife","Granada","Las Palmas","Huesca",
                       "Oviedo","Burgos"),
            Asist2 = c(6643L,8058L,6150L,6249L,
                       5628L,6315L,5649L,7258L,5245L)
)

And this is my code:

ggplot(asis, aes(x= factor(City, level = c("Ibiza","Barcelona",
                                           "Zaragoza","Tenerife","Granada","Las Palmas","Huesca",
                                           "Oviedo","Burgos")))) +
        geom_line(aes(y = `Asist1`), size = 1, color = "#69b3a2", group = 1) + 
        geom_line(aes(y = `Asist2`), size = 1, color = "Green", group = 1) +
        theme_ipsum() +
        xlab("")

Plot is fine but without legend. I use factor in x label to reorder x axe, is there an easier way to do it?

legends are there to describe aesthetic mappings aes( *things here *). then scales can be used to set what the data markers map to aesthetically.

also ggplot2 is designed with the concept of 'tidydata' in mind; so its best to transform your data to conform to that.

asis  <- data.frame(
  stringsAsFactors = FALSE,
  Jor = c(2L, 4L, 5L, 7L, 9L, 11L, 14L, 16L, 18L),
  Asist1 = c(5643L,7152L,5650L,5749L,
             5128L,5815L,5149L,6258L,4645L),
  City = c("Ibiza","Barcelona",
           "Zaragoza","Tenerife","Granada","Las Palmas","Huesca",
           "Oviedo","Burgos"),
  Asist2 = c(6643L,8058L,6150L,6249L,
             5628L,6315L,5649L,7258L,5245L)
)

asis <- mutate(asis,
               city_fac = factor(City, level = c("Ibiza","Barcelona",
                          "Zaragoza","Tenerife","Granada","Las Palmas","Huesca",
                          "Oviedo","Burgos")))

asis_2 <- pivot_longer(asis,
                       cols=starts_with("Asis"),
                       names_to = "name as seen in legend")
  ggplot(asis_2, aes(x=city_fac)) +
  geom_line(aes(y = value,
                color=`name as seen in legend`,
                group=`name as seen in legend`), linewidth = 1) +
  xlab("") +
    scale_color_manual(values=c("Asist1"="#69b3a2",
                                "Asist2"="green"))
2 Likes

Thanks as always nirgrahamuk. Works fine.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.