使用geom_point时出现错误“ geom_point需要以下美感:y”

时间:2019-08-14 23:21:27

标签: r ggplot2 rgraph

我需要从数据框中绘制几列。一般来说,在此图表中,我需要将三个选定列的值绘制为一行,其中X表示 Release 列,根据以下数据框:

Release,AddedClasses,ModifiedClasses,RemovedClasses,AddedMethods,ModifiedMethods,RemovedMethods,AddedImports,RemovedImports,AddedFields,ModifiedFields,RemovedFields
v1,39,33,0,43,25,0,3,0,21,0,0
v2,48,62,0,88,56,1,35,0,42,0,2
v3,54,93,0,117,95,1,67,0,67,0,2
v4,55,116,29,124,134,5,69,2,121,0,5

对于行,我需要从以下列中绘制值:AddedClassesModifiedClassesRemovedClasses

我尝试使用以下代码绘制图形:

ggplot(data=ReminderDOPTransformationsResume, aes(x=Release, group = 1)) + 
geom_line(aes(y=AddedClasses,color=AddedClasses), size=2) + 
geom_point(aes(color = AddedClasses), size=5, stroke = 0, shape = 16) + 
geom_line(aes(y=ModifiedClasses,color=ModifiedClasses), size=2) + 
geom_point(aes(color = ModifiedClasses), size=5, stroke = 0, shape = 16) + 
geom_line(aes(y=RemovedClasses,color=RemovedClasses), size=2) + 
geom_point(aes(color = RemovedClasses), size=5, stroke = 0, shape = 16) + 
scale_linetype_manual(values=c("solid", "solid")) +
theme_bw(base_size = 24) + theme(plot.title = element_text(hjust = 0.5), legend.title=element_blank()) 

但是在执行时,会显示以下错误:

Error: geom_point requires the following missing aesthetics: y

如果我删除了geom_point部分,则会绘制图形,但是线条颜色和标题会出现错误:

enter image description here

1 个答案:

答案 0 :(得分:2)

将数据从“宽”格式转换为“长”格式-一列用于变量名,另一列用于变量名-aes()将为您完成所有工作。

library(dplyr)
library(tidyr)
library(ggplot2)

ReminderDOPTransformationsResume <- tibble(Release = paste0("v", 1:4), 
                                           AddedClasses = c(39, 48, 54, 55), 
                                           ModifiedClasses = c(33, 62, 93, 116),
                                           RemovedClasses = c(0, 0, 0, 29),
                                           AddedMethods = c(43, 88, 117, 124))

ReminderDOPTransformationsResume %>% 
  select(Release, AddedClasses, ModifiedClasses, RemovedClasses) %>% 
  gather(Var, Val, -Release) %>% 
  ggplot(aes(Release, Val, group = Var)) + 
  geom_line(aes(color = Var)) + 
  geom_point(aes(color = Var))

结果:

enter image description here