我的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指数的传说。非常感谢您的及时帮助。
我的建议是以“整洁”的方式重塑数据,这样可以避免将来遇到很多麻烦(不仅是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)