0

After referring to multiple links i have got to the below code however i still am not succeeding to get the line with labels. I suspect some mistake in sec.axis transformation but i can't figure it out.

# dummy data
df_dummy = data.frame('Plan_code'=c('A','B','C','D','E','F','G'),
'Total'=c(191432,180241,99164,58443,56616,29579,19510),'STP'=c(41,40,44,37,37,37,45))

# creation of plot 
[![g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
  geom_col(aes(fill = 'Total')) +
  geom_line(data = df_dummy, aes(x = Plan_code, y = STP,group=1)) +
  geom_point(data = df_dummy, aes(x = Plan_code,y=STP)) +
  geom_label(data = df_dummy, aes(x = Plan_code, y = STP, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
  scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT')) +
labs(fill = NULL, color = NULL) +
  theme_minimal()
print(g)][1]][1]

plot

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Learner_seeker
  • 544
  • 1
  • 4
  • 21

1 Answers1

1

Like that?

g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
     geom_col(aes(fill = 'Total'))  +
     geom_point(data = df_dummy, aes(x = Plan_code,y=STP * 2000)) +
     geom_label(data = df_dummy, aes(x = Plan_code, y = STP *2000, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
     scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT'))+
     geom_line(data = df_dummy, aes(x = Plan_code, y = STP * 2000,group=1), col = 'blue') +
     theme(axis.text.y.right = element_text(color =  'blue'),axis.title.y.right = element_text(color =  'blue'))
     labs(fill = NULL, color = NULL) +
     theme_minimal()

I just multiplied your data with 2000, so that the absolute y-coordinates were right. And I changed the color.

Max Teflon
  • 1,760
  • 10
  • 16
  • Looks close to what i wanted ~ could you explain more on the reasoning to multiply 2000 ? Also could i get the labels near the points - i tried adjusting the vjust and getting it up but it wasnt working for me. I took this code snippet from another stack over flow post and hence i do not need the color coding as well for A,B,C etc – Learner_seeker Jun 13 '19 at 09:03
  • The reasoning behind the multiplication is just the reverse of what you did in creating the second axis. You devided your Axis-Labels by 2000 so that they would show percentage-values. You did not really introduce a second scale, the 'absolute' y-values stayed the same. So, to display your percentage-values in the right relative distance, you have to transform them to your 'absolute' y-scale, i.e. your total-axis. – Max Teflon Jun 13 '19 at 09:18
  • I changed the label y in the same way, following the same reasoning. At first, I thought you had your labels down there on purpose. (reminescent of [this](https://stackoverflow.com/questions/56543485/plot-coloured-boxes-around-axis-label/56543751#56543751) Question) – Max Teflon Jun 13 '19 at 09:19