我正在尝试在ggplot2中绘制随机测试分数数据。分数按考试、年份和年级细分。当我运行下面的脚本时,Y 轴显示一个不需要的范围。也就是说,范围是无序的,而我希望它以固定的间隔从低到高排序。通常,ggplot2 默认执行此排序,但我不知道的数据框或设置导致这种情况不会发生。
grade <- rep(c(5,6,7,8,9),times=6)
years <- rep(c(2008,2009,2010), each=10)
tests <- rep(c("English","Math"),times=3,each=5)
scores <- c(3.3,7.6,10.8,4.8,3.0,-2.8,14.8,12.4,0.3,6.0,7.0,3.1,3.7,-0.5,0.6,6.2,9.6,5.3,1.9,1.3,1.1,0.0,5.5,6.2,0.3,-0.4,2.2,4.9,4.7,2.6)
data2 <- data.frame(cbind(years,grade,tests,scores))
graph_2 <- ggplot(data=data2, aes(x=years, y=scores)) +
geom_point(aes(color=factor(interaction(grade,tests)),size=1)) +
geom_line(aes(group=interaction(tests,grade), color=factor(interaction(grade,tests)))) +
facet_grid(. ~ grade)
graph_2
我想也许 ggplot2 认为数据是离散的,但是当我尝试is.factor(scores)
时,R 控制台返回FALSE
。
问题出在您的数据上,而不是ggplot()
上。创建数据框时,您在data.frame()
中使用了函数cbind()
。这使您的所有列都成为因子,因为函数cbind()
在这种情况下生成矩阵,所有数据都是相同类型的 - 字符。函数data.frame()
创建数据框,但所有字符列都转换为因子。
data2 <- data.frame(cbind(years,grade,tests,scores))
str(data2)
'data.frame': 30 obs. of 4 variables:
$ years : Factor w/ 3 levels "2008","2009",..: 1 1 1 1 1 1 1 1 1 1 ...
$ grade : Factor w/ 5 levels "5","6","7","8",..: 1 2 3 4 5 1 2 3 4 5 ...
$ tests : Factor w/ 2 levels "English","Math": 1 1 1 1 1 2 2 2 2 2 ...
$ scores: Factor w/ 28 levels "-0.4","-0.5",..: 17 27 10 20 15 3 12 11 5 24 ...
如果删除cbind()
,则数字列将被视为数字,并且绘图看起来符合预期。
data2 <- data.frame(years,grade,tests,scores)
str(data2)
'data.frame': 30 obs. of 4 variables:
$ years : num 2008 2008 2008 2008 2008 ...
$ grade : num 5 6 7 8 9 5 6 7 8 9 ...
$ tests : Factor w/ 2 levels "English","Math": 1 1 1 1 1 2 2 2 2 2 ...
$ scores: num 3.3 7.6 10.8 4.8 3 -2.8 14.8 12.4 0.3 6 ...