在ggplot2中绘制线条和群体审美 [英] Plotting lines and the group aesthetic in ggplot2

查看:140
本文介绍了在ggplot2中绘制线条和群体审美的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自之前的一个:


重要的是[横轴上的一个因子的图表]是手动指定分组。通过
默认ggplot2使用
中的所有分类变量的组合来对geom进行分组 - 这对于该分块不起作用,因为
为每个分数获取单独一行。手动指定group = 1
表示您想要一条连线连接所有点。


实际上可以将点非常不同的方式 koshke在此演示

This question follows on from an earlier question and its answers.

First some toy data:

df = read.table(text = 
"School      Year    Value 
 A           1998    5
 B           1999    10
 C           2000    15
 A           2000    7
 B           2001    15
 C           2002    20", sep = "", header = TRUE)

The original question asked how to plot Value-Year lines for each School. The answers more or less correspond to p1 and p2 below. But also consider p3.

library(ggplot2)

(p1 <- ggplot(data = df, aes(x = Year, y = Value, colour = School)) +       
   geom_line() + geom_point())

(p2 <- ggplot(data = df, aes(x = factor(Year), y = Value, colour = School)) +       
  geom_line(aes(group = School)) + geom_point())

(p3 <- ggplot(data = df, aes(x = factor(Year), y = Value, colour = School)) +       
  geom_line() + geom_point())

Both p1 and p2 do the job. The difference between p1 and p2 is that p1 treats Year as numeric whereas p2 treats Year as a factor. Also, p2 contains a group aesthetic in geom_line. But when the group aesthetic is dropped as in p3, the lines are not drawn.

The question is: Why is the group aesthetic necessary when the x-axis variable is a factor but the group aesthetic is not needed when the x-axis variable is numeric?

解决方案

In the words of Hadley himself:

The important thing [for a line graph with a factor on the horizontal axis] is to manually specify the grouping. By default ggplot2 uses the combination of all categorical variables in the plot to group geoms - that doesn't work for this plot because you get an individual line for each point. Manually specify group = 1 indicates you want a single line connecting all the points.

You can actually group the points in very different ways as demonstrated by koshke here

这篇关于在ggplot2中绘制线条和群体审美的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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