【问题标题】:Full manual legend with shape, linetype, labels defined in ggplot2在 ggplot2 中定义的具有形状、线型和标签的完整手动图例
【发布时间】:2016-11-18 11:50:14
【问题描述】:

我已经使用以下命令构建了一个包含每月温度数据的图。在这里,我需要添加一个具有定义形状(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

【问题讨论】:

  • 你能分享一个小样本可重现的数据吗?
  • scale_shape_manual(values = c(16,17,19)) 正确的调用方式?同样适用于 linetype_manual()
  • 您好,我在帖子中添加了一部分数据。

标签: r ggplot2 themes legend


【解决方案1】:

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

第二个问题是,如果您希望 shape、fill 和 linetype 出现在图例中,则需要将它们包含在您的 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 有很棒的例子。

【讨论】:

  • 谢谢。我已经添加了我的数据。抱歉,您构建的代码不适用于我的数据结构。我可以要求您更新您的代码以适合我的数据集。非常感谢。
  • 更新代码以适应您的变量非常容易。在寻求帮助之前,请务必尝试自己做。更新的代码在上面
猜你喜欢
  • 2016-08-05
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
  • 2011-11-11
相关资源
最近更新 更多