将点与双轴中的相应条对齐

Align point to corresponding bar in dual axis

如何使用 ggplot,将 geom_point 与其对应的条对齐,并为这些点添加黑色轮廓。下面是最小代码及其输出。

temp_mpg <- mpg %>% group_by(year, manufacturer) %>% summarise(displ = first(displ),
                                                               cty = first(cty)) 

coeff <- max(temp_mpg$cty) / max(temp_mpg$displ)

temp_mpg %>% ggplot(aes(x = manufacturer, fill=as.factor(year))) +
  geom_bar( aes(y = displ), 
            stat="identity", position='dodge',
            color="black") +
  geom_point( aes(y = cty / coeff, color = as.factor(year)), 
              size = 4) +
  scale_y_continuous(
    sec.axis = sec_axis(~(.) * coeff)
  ) + 
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90)
  )

输出:

您可以在 geom_point() 中添加一个对齐位置。对于黑色轮廓,设置shape = 21然后将变量映射到填充。

temp_mpg %>% ggplot(aes(x = manufacturer, fill=as.factor(year))) +
  geom_bar( aes(y = displ), 
            stat="identity", position='dodge',
            color="black") +
  geom_point( aes(y = cty / coeff, fill = as.factor(year)), 
              size = 4, shape = 21, position = position_dodge(0.9)) +
  scale_y_continuous(
    sec.axis = sec_axis(~(.) * coeff)
  ) + 
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90)
  )

正如我从文档中了解到的那样,默认条形宽度是数据分辨率的 90%,因此 0.9 可能是闪避宽度的不错选择。