ggplot2 折线图给出了“geom_path:每组仅包含一个观察值.需要调整群体审美吗?" [英] ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

查看:52
本文介绍了ggplot2 折线图给出了“geom_path:每组仅包含一个观察值.需要调整群体审美吗?"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这个数据框(df"):

With this data frame ("df"):

year pollution
1 1999 346.82000
2 2002 134.30882
3 2005 130.43038
4 2008  88.27546

我尝试创建这样的折线图:

I try to create a line chart like this:

  plot5 <- ggplot(df, aes(year, pollution)) +
           geom_point() +
           geom_line() +
           labs(x = "Year", y = "Particulate matter emissions (tons)", title = "Motor vehicle emissions in Baltimore")

我得到的错误是:

geom_path:每组只包含一个观察.你需要吗调整群体审美?

geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?

即使我想要折线图,图表也显示为散点图.我试图用 geom_line(aes(group = year)) 替换 geom_line() ,但这没有用.

The chart appears as a scatter plot even though I want a line chart. I tried to replace geom_line() with geom_line(aes(group = year)) but that didn't work.

在一个回答中,我被告知将年份转换为因子变量.我做了,问题仍然存在.这是 str(df)dput(df) 的输出:

In an answer I was told to convert year to a factor variable. I did and the problem persists. This is the output of str(df) and dput(df):

'data.frame':   4 obs. of  2 variables:
 $ year     : num  1 2 3 4
 $ pollution: num [1:4(1d)] 346.8 134.3 130.4 88.3
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr  "1999" "2002" "2005" "2008"

structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82, 
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
    c("1999", "2002", "2005", "2008")))), .Names = c("year", 
"pollution"), row.names = c(NA, -4L), class = "data.frame")

推荐答案

您只需要将 group = 1 添加到 ggplot 或 geom_line aes() 中即可.

You only have to add group = 1 into the ggplot or geom_line aes().

对于折线图,必须对数据点进行分组,以便知道要连接哪些点.在这种情况下,很简单——所有的点都应该连接起来,所以 group=1.当使用更多的变量并绘制多条线时,线的分组通常由变量完成.

For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.

参考:R 手册,章节:图形 Bar_and_line_graphs_(ggplot2),折线图.

试试这个:

plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
         geom_point() +
         geom_line() +
         labs(x = "Year", y = "Particulate matter emissions (tons)", 
              title = "Motor vehicle emissions in Baltimore")

这篇关于ggplot2 折线图给出了“geom_path:每组仅包含一个观察值.需要调整群体审美吗?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆