带有在 ggplot2 中定义的形状、线型和标签的完整手动图例

Full manual legend with shape, linetype, labels defined in ggplot2

我已经使用以下命令构建了一个包含每月温度数据的图表。在这里,我需要添加一个具有定义形状(16、17、18...)、线型(1,1,2,...)和标签(1977、1978、1979...)的图例。我尝试了不同的方法,但没有想到没有导致任何错误。

这里是我的一部分数据

 structure(list(month = structure(1:12, .Label = c("Jan", "Feb", 
"Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", 
"Dec"), class = "factor"), X1977 = c(10.3, 11.8, 15.4, 18.7, 
20.3, 22, 23.5, 24.5, 20.1, 17.2, 15.2, 16.5), X1978 = c(10.3, 
8, 10.8, 16.9, 20.2, 20.3, 20, 20, 17.9, 16.4, 11.4, 12.9), X1979 = c(13.9, 
12, 13.4, 17.5, 19.6, 20.3, 19.3, 19.3, 18.3, 16.1, 14.5, 10.6
)), .Names = c("month", "X1977", "X1978", "X1979"), class = "data.frame",row.names = c(NA, 
-12L))


    p <- ggplot(t.df, aes(month, X1977)) 
    p
    p <-p + geom_point(aes(month, X1977),shape=16) + geom_line(aes(x=1:12, y= X1977))
    p <- p+ geom_point(aes(month, X1978),shape=17) + geom_line(aes(x=1:12, y= X1978))
    p <- p+ geom_point(aes(month, X1979),shape=18) + geom_line(aes(x=1:12, y= X1979), linetype=2)
    p2 <- p+ labs(x="Month", y="Mean Temperature")
    p2

    p2 + theme(legend.position = "right")+
         scale_fill_manual(labels=c("1977", "1978", "1979"))+
         scale_linetype_manual(1,1,2)+ scale_shape_manual(16,17,19)
     # this code does not yield error but legend is not added on the plot

首先是您的数据似乎是宽格式(您的时间序列在不同的列中)。 ggplot2 最适合长格式,您的数据位于键值对中。您可以使用 tidyr 包转换数据,特别是使用函数 gatherspread.

第二个问题是,如果您希望 shapefilllinetype 出现在图例中,您需要将它们包含在 aes() 调用中。在您的代码中没有 fill aes,因此您需要包含它。

解决方案如下:

library(tidyr) 
library(ggplot2)

plot_data <- gather(df, year, temperature, X1977, X1978, X1979)


ggplot(plot_data, aes(x = month, y = temperature, color = year)) +
  geom_point(aes(shape = year)) +
  geom_line(aes(linetype = year, group = year)) +
  labs(x = "Month", y = "Mean Temperature") +
  theme(legend.position = "right") +
  scale_fill_manual(labels = c("1977", "1978","1979"), breaks = c("X1977","X1978","X1979"), values = c("red","green","blue")) +
  scale_linetype_manual(values = c("X1977" = 1, "X1978" = 1, "X1979" = 2)) +
  scale_shape_manual(values = c("X1977" = 16, "X1978" = 17, "X1979" = 18))

注意天平是如何使用的。 ggplot2 documentation site 有很好的例子。