我有一个问题,我在韩国的七个大城市的多面多线图的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指数’变量的图例。如果有人能加入进来,并找出另一种方法来做这件事,我将不胜感激。
请参考我没有图例的多面板图,以更深入地了解我正在寻找的内容:

发布于 2020-02-11 15:29:06
我的建议是以一种“整洁”的方式重塑你的数据,这将避免你在未来遇到很多麻烦(不仅仅是使用ggplot2)。请参阅this精彩文档。
这里的问题不是facet_grid()函数,而是告诉ggplot2要包含在图例中的数据的方法;这些数据必须在aes()中。
由于您没有提供可重现的数据集,因此我使用包含在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
# 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_plot2

发布于 2020-02-16 15:17:23
这就是我如何调整我的代码,以获得我想要的多面板绘图。感谢datanovia为我们提供了很好的参考资料!我还包括了一个传说。
dahir %>% filter(is.na(Year) == FALSE) %>%
ggplot(dahir, mapping = aes(x = Year, y = value)) +
geom_line(size = 1.2, aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue"))+
labs(y="Index: 2012=100",
title = "Decoupling by City")+
facet_wrap (~City)https://stackoverflow.com/questions/60161176
复制相似问题