Выровняйте точку по соответствующему стержню на двойной оси - PullRequest
0 голосов
/ 01 апреля 2020

Используя 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)
  )

Вывод: enter image description here

1 Ответ

2 голосов
/ 01 апреля 2020

Вы можете добавить позицию к вашему 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)
  )

enter image description here

Как я понял из документации, a ширина полосы по умолчанию составляет 90% от разрешения данных, поэтому, вероятно, 0,9 является хорошим выбором для ширины уклонения.

...