简体   繁体   中英

Adding a secondary legend for linetype in ggplot

So basically my plot is almost done except a second linetype legend that distinguish social media platforms I would like to add. Could anyone check why the code does not work (the second legend does not pop up)? Thank you!

library(ggplot2)

country <- read.csv("http://sanhochung.com/wp-content/uploads/2021/02/social_media_by_country.csv")

ggplot(data = country, aes(x = Year, y = instagram)) +
  geom_line(aes(color = Country)) +
  geom_line(data = country, aes(x = Year, y = facebook, color = Country), linetype = "longdash")+
  geom_line(data = country, aes(x = Year, y = twitter, color = Country), linetype = "dotted")+
  labs(title="Total percentage of national population using social media",
       x ="Year", y = "Percentage of platform user", caption = "Source: datareportal.com, self-reported by internet users in January") +
          ylim(0, 100)+
  theme(plot.title = element_text(hjust = 0.5))+
  scale_linetype_manual(name = "Platform",
                    values = c("longdash","solid", "dotted"),
                    breaks = c("Facebook", "Instagram", "Twitter"),
                    guide = guide_legend(override.aes = list(linetype = c("longdash","solid", "dotted"),
                                                            color = "black")))

Getting data in long format should solve/simplify lot of your problems, also include linetype inside aes to get the legend.

library(ggplot2)

X <- read.csv("http://sanhochung.com/wp-content/uploads/2021/02/social_media_by_country.csv")

X %>%
  tidyr::pivot_longer(cols = facebook:instagram) %>%
  ggplot(aes(x = Year, y = value, color = Country, linetype = name)) +
  geom_line()  + geom_point(aes(shape = name)) + 
  labs(title="Total percentage of national population using social media",
       x ="Year", y = "Percentage of platform user", 
       caption = "Source: datareportal.com, self-reported by internet users in January") +
  ylim(0, 100)+
  theme(plot.title = element_text(hjust = 0.5))+
  scale_linetype_manual(name = "Platform",
                        values = c("longdash","solid", "dotted"),
                        breaks = c("facebook", "instagram", "twitter")) + 
  scale_shape_manual(name = "Platform", 
                     values = 1:3,
                     breaks = c("facebook", "instagram", "twitter"))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM