简体   繁体   English

在 ggplot 中为线型添加辅助图例

[英]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.所以基本上我的 plot 几乎完成了,除了我想添加的区分社交媒体平台的第二个线型图例。 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.以长格式获取数据应该可以解决/简化您的许多问题,还包括aes中的linetype以获取图例。

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"))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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