简体   繁体   English

如何使用 ggplot2 在 R 中连接它们之间的数据表中的点?

[英]How to connect points in datatable between them in R using ggplot2?

I took data from this site CO2 emission我从该站点获取了二氧化碳排放量的数据

Reshaping重塑

df_reshaped <- data.frame(Countries = df$Country,                           
                          CO2 = c(df$X2018, df$X2017, df$X2016),
                          year = c(rep("X2018", nrow(newdf)),
                                    rep("X2017", nrow(newdf)),
                                    rep("X2016", nrow(newdf))))

# head(df_reshaped)

            Countries     CO2  year
1               China 9663.36 X2018
2       United States 4749.57 X2018
3 European Union (27) 2636.99 X2018
4               India 2400.25 X2018
5           Indonesia 1269.55 X2018
6               Japan 1074.08 X2018

If I try to vizualize data如果我尝试可视化数据

ggplot(df_reshaped, aes(year, CO2, group=1, col = Countries)) +  geom_point() + geom_line()

这样出去

I need to connect line each country in correct way.我需要以正确的方式连接每个国家/地区。

As @stefan also mentioned in the comments, you should use group = countries .正如@stefan 在评论中也提到的那样,您应该使用group = countries You can use the following code:您可以使用以下代码:

library(tidyverse)
ggplot(aes(year, CO2, group = Countries, col = Countries)) +
  geom_point() +
  geom_line()

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM