在图表上绘制多条线:geom_path:每组仅包含一个观测值。您是否需要调整小组审美?

我试图在图表上绘制多条线,我的代码如下所示:

ggplot(Data_UK_onTrea,aes(x = years,y = value )) +
  geom_line(aes(color = region,linetype = sex))

我的数据显示如下:

structure(list(years = structure(c(1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,1L,10L),.Label = c("2009","2010","2011","2012","2013","2014","2015","2016","2017","2018"),class = "factor"),region = structure(c(1L,4L),.Label = c("England","Wales","Northern Ireland","Scotland"),sex = c("Male","Male","Female","Female"),value = c(39611,42188,44874,47665,50100,53018,56121,58005,59600,60168,884,996,1114,1158,1256,1411,1480,1548,1625,1695,322,366,444,511,592,633,734,787,861,894,2149,2314,2538,2665,2914,2962,3100,3162,3385,3494,20868,21999,23102,23995,24542,25686,26289,26773,27376,27662,320,340,384,400,426,453,463,481,491,509,126,135,138,160,179,181,211,221,224,236,961,1031,1109,1124,1157,1160,1195,1206,1284,1304)),class = "data.frame",row.names = c(NA,-80L))

但是当我运行代码时,图表上没有线:

enter image description here

我将不胜感激。

zas135421 回答:在图表上绘制多条线:geom_path:每组仅包含一个观测值。您是否需要调整小组审美?

最简单的解决方案是将years从一个因子更改为一个数字变量

Data_UK_onTrea$years <- as.numeric(as.character(Data_UK_onTrea$years))

ggplot(Data_UK_onTrea,aes(x = years,y = value )) +
  geom_line(aes(color = region,linetype = sex))

line graph

,

“年”列是一个因素:

> str(Data_UK_onTrea)
'data.frame':   80 obs. of  4 variables:
 $ years : Factor w/ 10 levels "2009","2010",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ region: Factor w/ 4 levels "England","Wales",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ sex   : chr  "Male" "Male" "Male" "Male" ...
 $ value : num  39611 42188 44874 47665 50100 ...

现在将年份转换为数字:

Data_UK_onTrea$years = as.numeric(as.character(Data_UK_onTrea$years)) 

ggplot(Data_UK_onTrea,linetype = sex))

enter image description here

我不确定您如何得出一个因子,但是您在执行read.table时可以指定stringsAsFactors = F,也可以执行上述str()来检查变量。

本文链接:https://www.f2er.com/3114402.html

大家都在问