-1

I a trying to replicate what can be easily done in an excel. Using ggplot, I tried to plot the following:

  1. Plot a barchart, where the left Y axis is represented in counts (0-600)
  2. plot a line graph where the right Y axis is represented in % (0-100).

qn1 . Can someone explain to me, how can I link my percentage data to my secondary axis? Currently the line graph (which should represent the %) is plotted based on the primary Y axis using the counts scale.

qn2. How can i change the 2 scales independently?

qn3. How can i name the 2 scales independently?

ggplot() +
  geom_bar(data=data,aes(x=sch,y=count,fill=category),stat = "identity")+ 
  scale_fill_manual(values=c("darkcyan", "indianred1")) +
  geom_line(data=data_percentage, aes(x=sch, y=count, group=1)) + 
  geom_point(data=data_percentage, aes(x=sch, y=count, group=1)) +
  geom_text(data=data_percentage,aes(x=scht,label=paste(count,"%",sep="")),size=3) +
  scale_y_continuous(sec.axis = sec_axis(~./2), name="%")+
  theme(panel.background = element_blank(), 
        axis.line = element_line(colour = "black", size = 0.5, linetype = "solid"), 
        plot.title = element_text(size=11, face="bold", hjust=0.3), 
        legend.position = "top", legend.text = element_text(size=9)) +
  labs(fill="") + guides(fill = guide_legend(reverse=TRUE))+
  ylab("No. Recruited") + ggtitle("2. No. of students")
  • @PalvinderKaur There exist *a lot* of questions and excellent answers around each of your 3 questions here on SO. Please spend some time researching before posting here. It also good advice to stick to the one-question-per-post rule. – Maurits Evers Sep 12 '18 at 05:06
  • @Tino Thank you Tino. I will look at this example and try it out. – Palvinder Kaur Sep 12 '18 at 05:54

1 Answers1

2

Answer1: You don't link the geom to an axis. Instead, you scale it up or down to be consistent with your secondary axis scale. In the example you provided, sec.axis is scaled by ~./2 then your y aesthetic in both geom_line and geom_point should be count*2. This will give and appearance that the line is linked to the secondary axis.

Answer2: You can't. In ggplot, the secondary axis should be a one-to-one transformation of the primary axis. I don't know if another package could do that.

Answer3: just move the name argument within the function scale_y_continuous to inside the function sec_axis as the example code shown below.

The code will look something like this:

ggplot() +
  .
  .
  geom_line(data = data_percentage, aes(x=sch, y=count*2, group=1)) +
  geom_point(data = data_percentage, aes(x=sch, y=count*2, group=1)) + 
  .
  .
  scale_y_continuous(sec.axis = sec_axis(~./2, name="%"))+
  .
  . 
  .
Abdallah Atef
  • 661
  • 1
  • 6
  • 14