我如何将图例添加到多面多面的ggplot中?

问题描述 投票:0回答:1

我的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指数的传说。非常感谢您的及时帮助。

以下是我的不带图例的ggplot:enter image description here

ggplot2 legend facet-wrap facet-grid line-plot
1个回答
0
投票

我的建议是以“整洁”的方式重塑数据,这样可以避免将来遇到很多麻烦(不仅是ggplot2)。请参见this精美的文档。由于您没有提供可复制的数据集,因此我使用了RStudio中包含的mtcars数据集。只需复制粘贴下面的代码,它就会运行。

# 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

# my advice is to 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)
© www.soinside.com 2019 - 2024. All rights reserved.