r - geom_bar 和 geom_point 在同一个 ggplot 和同一个组内
问题描述
我有当前代码
ggplot(data = niveles[niveles$departamento=="CUNDINAMARCA" &
niveles$prueba=="MATEMÁTICAS" &
!is.na(niveles$nivel),]) +
geom_bar(stat="identity", position = position_dodge(),
aes(x = año, y = desempeño, fill = nivel)) +
geom_point(data = niveles[niveles$prueba=="MATEMÁTICAS" &
niveles$departamento=="COLOMBIA" &
!is.na(niveles$nivel),], shape = 24,
aes(x = año, y = desempeño, group = nivel, fill = "blue"))
这给了我以下情节:
但是,我希望获得每个“点”及其对应的“niveles”变量类别。有谁知道我该怎么做?
提前问候。
解决方案
您可以像使用闪避条一样闪避点position=position_dodge()
。但是,您需要添加一个width
参数来指定要“躲避”多少。值 1 应与闪避的条对应。您在图例中还有一个未知的“蓝色”类别。那是因为fill
论点应该出现在审美之外(aes
)
我还认为您应该首先对数据进行子集化,而不是在 ggplot 命令中执行所有操作。
另一种方法是按部门分面(参见下面的选项 2)。
但首先要闪避点。
选项 1:子集
为 prueba 创建一个子集,为 nivel 创建一个子集:
MATH <- niveles[niveles$prueba=="MATEMÁTICAS" & !is.na(niveles$nivel),]
为每个部门创建子集:
CUNDINAMARCA <- MATH[MATH$departamento=="CUNDINAMARCA",]
COLOMBIA <- MATH[MATH$departamento=="CUNDINAMARCA",]
然后制作你的图表:
ggplot(data = CUNDINAMARCA) +
geom_bar(stat="identity", position = position_dodge(),
aes(x = año, y = desempeño, fill = nivel)) +
geom_point(data = COLOMBIA, shape = 24,
position = position_dodge(width=1), # You need this to align points with bars
aes(x = año, y = desempeño, group = nivel), fill = "blue")
我无法在您的数据上对其进行测试,但我以 mtcars 数据集为例。
mtcars <- mtcars %>%
mutate(gear=factor(gear), cyl=factor(cyl))
VS0 <- mtcars[mtcars$vs==0,]
VS1 <- mtcars[mtcars$vs==1,]
ggplot() +
geom_bar(data = VS0, stat="identity", position = position_dodge(),
aes(x = cyl, y = mpg, fill = gear)) +
geom_point(data = VS1, shape = 24,
position = position_dodge(width=1),
aes(x = cyl, y = mpg, group = gear), fill = "blue")
选项 2:刻面
ggplot(data = mtcars, group=vs) +
geom_bar(stat="identity", position = position_dodge(),
aes(x = cyl, y = mpg, fill = gear)) +
facet_grid(~vs, labeller=label_both)
对于您的数据,也许这会起作用:
DATA <- MATH[MATH$departamento %in% c("CUNDINAMARCA","COLOMBIA"),]
ggplot(data = DATA, group=departamento) +
geom_bar(stat="identity", position = position_dodge(),
aes(x = año, y = desempeño, fill = nivel)) +
facet_grid(~departamento, labeller=label_both)
推荐阅读
- javascript - chrome.tabs.sendMessage 不向内容脚本发送消息
- laravel - Laravel 雄辩加入最后一条记录
- java - java - 如何在java spring boot中对json数组的两个值求和?
- javascript - 如何控制“日期”输入小部件的“onchange”事件?
- php - 从事件订阅者重定向
- javascript - 使用 jquery 或 javascript 为父子属性创建手风琴式下拉菜单
- android - 如何在 Firebase ML kit Android 中正确绘制检测到的面部边界框?
- web-scraping - 在登录页面中使用 FormRequest 登录没有任何效果(重定向 302)
- python - python - 如何使用shutil.make_archive()在python中创建没有文件扩展名的zip存档?
- python - 在 div 类下抓取子 div