R ggplot运行报错Aesthetics长度需为1或与数据一致问题求解
R ggplot报错“Aesthetics must be either length 1 or the same as the data”的原因与修正方案
报错原因
ggplot()中指定的绘图数据源data=elect是完整的368行数据集,ggplot默认要求aes()中映射的变量长度和传入的data行数完全一致。- 你单独提取的
austria_year、austria_rad_right都是长度为18的独立向量,和368行的elect长度不匹配,就会触发长度校验报错,和两个x/y向量本身长度是否一致无关。
修正方案
推荐优先使用第一种方法,后续扩展绘图需求时兼容性更强:
方法1:构造对应子集作为绘图数据源(规范写法)
# 提取奥地利对应数据构造独立子集 austria_sub <- data.frame( year = elect$year[26:43], rad_right = elect$austria_rad_right[26:43] ) ggplot(data=austria_sub, aes(x=year, y=rad_right)) + geom_line() + xlab("Year") + ylab("Radical Right Vote Share") + ggtitle("Austria Radical Right Support Over Time") + theme_gray() + theme(panel.grid=element_blank())
方法2:不指定全局数据源,直接传入向量
austria_year <- elect$year[26:43] austria_rad_right <- elect$austria_rad_right[26:43] # 去掉data参数,ggplot会自动匹配传入向量的长度 ggplot(aes(x=austria_year, y=austria_rad_right)) + geom_line() + xlab("Year") + ylab("Radical Right Vote Share") + ggtitle("Austria Radical Right Support Over Time") + theme_gray() + theme(panel.grid=element_blank())
内容的提问来源于stack exchange,提问作者redleg_64
相关产品推荐
相关产品推荐

