如何只显示带有名称和线型的图例(删除左侧图层)?

How to only show the legend with the names and line type (remove the left layer)?

我已尝试找到答案并测试有关如何处理我的问题的不同建议。我需要图表来显示带有列名称的图例(I reshape2::melt(df) 之后的变量列)和线条样式。

我觉得这可能真的很容易,但我正在努力研究如何不重复这个传说。

我想知道如何制作一个左图例为线条样式,右图例为线条颜色的图例。对不起,如果之前已经回答过。

df <- bind_cols(c(1979:2019),sample(1:200,41),sample(1:200,41),sample(1:200,41),sample(1:200,41))
colnames(df) <- c("Dates","Column1","Column2",
                  "Column3","Column4")

ggplot(reshape2::melt(df, id.var = "Dates"), 
       aes(`Dates`,value,colour = variable,group = variable)) +
 # geom_point() +
  geom_line(aes(linetype=variable, colour = variable)) +
  scale_linetype_manual(values=c("solid","dotted", "twodash", "dashed")) + 
  theme_classic() +
  labs(x = " Period", y = "Number of X detected", color='', show.legend = F) +
  theme(axis.text.x = element_text(angle = 90, vjust = 1.5, hjust=1.5)) +
  scale_color_manual(values = c("steelblue3","red2", "darkgreen","pink")) +
  theme(legend.position = "bottom",legend.text = element_text(size = 13), 
        axis.text = element_text(size = 10),
        axis.title.x = element_text(size = 13),
        axis.title.y = element_text(size = 13),legend.title=element_blank())

如果你的意思是合并成一个图例,颜色和线型在四个变量中变化,那么确保两个 scale_ 给出相同的名称相应地匹配它们:

library(ggplot2)

df <- bind_cols(c(1979:2019),sample(1:200,41),sample(1:200,41),sample(1:200,41),sample(1:200,41))
colnames(df) <- c("Dates","Column1","Column2",
                  "Column3","Column4")

ggplot(reshape2::melt(df, id.var = "Dates"), 
       aes(`Dates`,value,colour = variable,group = variable)) +
  geom_line(aes(linetype=variable, colour = variable)) +
  scale_linetype_manual("", values=c("solid","dotted", "twodash", "dashed")) + 
  theme_classic() +
  labs(x = " Period", y = "Number of X detected") +
  theme(axis.text.x = element_text(angle = 90, vjust = 1.5, hjust=1.5)) +
  scale_color_manual("", values = c("steelblue3","red2", "darkgreen","pink")) +
  theme(legend.position = "bottom",legend.text = element_text(size = 13), 
        axis.text = element_text(size = 10),
        axis.title.x = element_text(size = 13),
        axis.title.y = element_text(size = 13),legend.title=element_blank())

如果我没有正确理解你的问题的话!

reprex package (v2.0.1)

于 2022-03-16 创建