首页 > 解决方案 > 向多行的 ggplot2 构面添加图例?

问题描述

我的 ggplot 对于韩国七个大都市区的多面多线图有问题。

我的 csv 数据集的结构类似于具有随时间变化的城市的横截面和时间序列维度的面板数据。

以下是我的数据集的格式:

Year   City    VKT index  GDP index 
2012   Seoul      100      100
2013   Seoul      94       105
2014   Seoul      96       110
..............................
2012   Busan      100      100
2013   Busan      97       105
..............................
2012   Daegu     100       100       
2013   Daegu     104       114

我的代码也如下:

deccity <- read_csv("decouplingbycity.csv")

deccity %>% filter(is.na(Year) == FALSE) %>%
ggplot(deccity, mapping = aes(x=Year)) +
  geom_line(size = 1, aes(y = `GDP index`), color = "darkred") +
  geom_line(size = 1,aes(y = `VKT index`), color="steelblue", linetype="twodash")+
  labs(y="Index: 1992=100",
       title = "Decoupling by city")+
  facet_wrap(~City)

你可以看到我现在得到的情节。但是有一个问题,明显的问题是我看不到“VKT 指数”和“GDP 指数”变量的图例。如果有人能插话并找出另一种方法来做到这一点,我将不胜感激。

请参考我的没有图例的多面板图,以更深入地了解我正在寻找的内容:

在此处输入图像描述

标签: ggplot2legendfacet-wrapfacet-gridline-plot

解决方案


我的建议是以“整洁”的方式重塑您的数据,这将避免您将来遇到很多麻烦(不仅是 ggplot2)。请参阅这个精彩的文档。

这里的问题不是facet_grid()函数,而是告诉 ggplot2 要包含在图例中的数据的方式;这个数据必须在里面aes()

由于您不提供可复制的数据集,因此我使用mtcarsRStudio 中包含的数据集。只需复制粘贴下面的代码,它就会运行。

# very usefull set of packages
library(tidyverse)

# here is what you are trying to do
ex_plot1 = ggplot(data = mtcars, aes(x = disp)) +
  geom_line(aes(y = mpg), color = "red") +
  geom_line(aes(y = qsec), color = "green")
plot(ex_plot1) # see there is no legend

# reshape your data this way:
ex_data2 = pivot_longer(data = mtcars, 
                        cols = c("mpg", "qsec"),
                        values_to = "values",
                        names_to = "colored_var")
# and then plot it, legend appears
ex_plot2 = ggplot(data = ex_data2, aes(x = disp, y = values, color = colored_var)) +
  geom_line()
plot(ex_plot2)

[编辑] 添加了输出

没有图例的情节,ex_plot1

没有图例的情节,ex_plot1

带有图例的情节,ex_plot2

带有图例的情节,ex_plot2


推荐阅读