0

Hi there: I can't quite get this graph the way I want. I know you're not supposed to graph two y-axes on one plot, but, this is for a class, and I'm going to be having students draw a predicted line on this graph. I need to have both y-axes centered at 0 and 50, respectively. Ideally, I would like to have the first y-axis graph extend to +7, as well, although that is not as necessary.


library(tidyverse)


date<-seq.Date(from=as.Date('1998-01-21'), to=as.Date('1998-02-1'), by='days')
tone<-c(-7.2, -6.3, -1.1, -2.8, 0.8, -2.5, 1.5,3.1, -0.4, 1.6, NA,NA)
popularity<-c(NA,58, 53, 56, 59, 60, 67,  70, 68, 69, 68, 72)
df<-data.frame(date, tone, popularity)
str(df)
library(scales)
df %>% 
  ggplot(., aes(x=date, y=tone))+geom_point()+geom_smooth(se=F)+ylim(c(-7,+7))+theme_bw()+labs(title="Media Coverage and Popularity of Presisdent Clinton in the Lewinsky Scandal")+scale_x_date()+scale_y_continuous(
    "tone", sec.axis =sec_axis(~ rescale(., to=c(0,100)), name="Approval")
  )

spindoctor
  • 1,719
  • 1
  • 18
  • 42

2 Answers2

0

How about using breaks in combination with limits inside scale_y_continuous()?

df %>% 
  ggplot(aes(date, tone)) + 
  geom_point() + 
  geom_smooth(se = F) + 
  theme_bw() + 
  labs(title = "Media Coverage and Popularity of Presisdent Clinton in the Lewinsky Scandal") + 
  scale_x_date() + 
  scale_y_continuous(
    "tone", 
    breaks = c(-7, 0, 7), 
    limits = c(-7, 7), 
    sec.axis = sec_axis(~ rescale(., to = c(0, 100)), name = "Approval")
  )

enter image description here

the-mad-statter
  • 5,650
  • 1
  • 10
  • 20
0

Instead of doing a transformation, duplicate (i.e. dup_axis() ) your original y-axis and change the labels in the duplicated plot.

df %>% 
  ggplot(., aes(x=date, y=tone))+geom_point()+
  geom_smooth(se=F)+
  theme_bw() + 
    labs(title="Media Coverage and Popularity of Presisdent Clinton in the Lewinsky Scandal") + 
    scale_x_date()+
    scale_y_continuous(breaks = c(-7, -3.5, 0, 3.5, 7), 
                       sec.axis = dup_axis(labels = c(0, 50, 100), 
                                           breaks = c(-7, 0, 7),
                                           name = "Approval")) +
  coord_cartesian(ylim = c(-7,7))

enter image description here

Nicolás Velasquez
  • 5,623
  • 11
  • 22