首页 > 解决方案 > 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”变量类别。有谁知道我该怎么做?

提前问候。

标签: rggplot2geom-bar

解决方案


您可以像使用闪避条一样闪避点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)

推荐阅读