使用手动形状和颜色创建图例

时间:2017-09-30 07:15:59

标签: r ggplot2 legend

我使用条形和线条来创建我的情节。演示代码是:

json_decode($your_json_string_here)

这会产生如下情节:

enter image description here

这个数字没有传说。我按照this的答案创建了一个自定义的图例但在我的情况下不起作用。我希望在我的图例中对应于条形和线条的正方形和线条形状。我们怎么能得到它?

我想要传奇,如下图所示: enter image description here

1 个答案:

答案 0 :(得分:2)

对于您要显示的数据类型,geom_bargeom_histogram更合适。当您操纵图例的应用程序时,需要将colour = ...部分放在aes内。为了获得所需的结果,最好对线条和条形使用不同类型的图例。通过这种方式,您可以更好地使用guide_legendoverride.aes更改图例的外观。

针对您的问题的建议:

ggplot(data = df) + 
  geom_bar(aes(x = timestamp, y = data1, colour = "black"),
           stat = "Identity", fill = NA) +
  geom_line(aes(x = timestamp, y = data2*150, linetype = "red"), colour = "red", size = 1) +
  scale_y_continuous(sec.axis = sec_axis(~./150, name = "data2")) +
  scale_linetype_manual(labels = "data2", values = "solid") +
  scale_colour_manual(name = "Parameter\n", labels = "data1", values = "black") +
  guides(colour = guide_legend(override.aes = list(colour = "black", size = 1),
                               order = 1),
         linetype = guide_legend(title = NULL,
                                 override.aes = list(linetype = "solid",
                                                     colour = "red",
                                                     size = 1),
                                 order = 2)) +
  theme_minimal() +
  theme(legend.key = element_rect(fill = "white", colour = NA),
        legend.spacing = unit(0, "lines"))

给出:

enter image description here