在ggplot2中使用带有标签的geom_line()进行绘图

问题描述 投票:-1回答:2

[我正在尝试使用ggplot2绘制此数据集,将每个国家/地区的名称放在每行geom_line()中,并在x轴(年份)和y轴(以及来自每个国家/地区的相关数据)中放置。

The DataSet to Edit

This is what I have so far. I wanted to include the name of the country in each line. The problem is that each country has its data in a separate column.

r ggplot2 label geom-text
2个回答
0
投票

如果要使用ggplot,则应将数据转换为“较长”格式。使用包tidyr

df %<>%
  pivot_longer(cols=matches("[^Year]"),
               names_to="Country", 
               values_to="Value")

给你

# A tibble: 108 x 3
    Year Country       Value
   <dbl> <chr>         <dbl>
 1  1995 Argentina   4122262
 2  1995 Bolivia     3409890
 3  1995 Brazil     36276255
 4  1995 Chile       2222563
 5  1995 Colombia   10279222
 6  1995 Costa_Rica  1611055
 7  1997 Argentina   4100563
 8  1997 Bolivia     3391943
 9  1997 Brazil     35718095
10  1997 Chile       2208382

基于此,很容易使用ggplot2为每个国家/地区绘制一条线:

ggplot(df, aes(x=Year, y=Value, color=Country)) + 
  geom_line()

0
投票

您有点回答了您的问题。您需要调整包装形状,以便将所有国家/地区合并到一个栏中。

    Year<-c(1991,1992,1993,1994,1995,1996)
Argentina<-c(235,531,3251,3153,13851,16513)
Mexico<-c(16503,16035,3516,3155,30351,16513)
Japan<-c(1651,868416,68165,35135,03,136816)

df<-data.frame(Year,Argentina,Mexico,Japan)

library(reshape2)

df2<- melt(data = df, id.vars = "Year", Cont.Val=c("Argentina","Mexico","Japan"))

library(ggplot2)

ggplot(df2, aes(x=Year, y=value, group=variable, color=variable))+
  geom_line()
© www.soinside.com 2019 - 2024. All rights reserved.