Skip to content

Secondary axis would not revert in ggplot version 3.1 #3165

Closed
@fa1therr

Description

@fa1therr

I am trying to build a bar and line graphs on the same plot but with the different y-axis. The y1 axis has limits 0 to 100 and y2 axis has limits from 4 to 1 (reversed). Hence, I am adding secondary axis for the line plot through scale_y_continuous(limits=c(0,100), sec.axis=(...)). I build a linear mapping from 0-100 to 4-1 through lm() and then fit the coefficients to the formula of sec.axis(). This works fine in ggplot 2.2.1 version whatever limits for secondary axis I put. However, in ggplot 3.1 the limits would not revert. Is it a bug?

#Data generation
Dimension <- c("Sales", "Image", "PR","Presentations","Observation")

#ImportanceToPercentOfRespondents <- c(90%, 60%, 50%, 30%, 20%)
ImportanceToPercentOfRespondents <-c(0.9,0.6,0.5,0.3,0.2) * 100

# Was the Goal of each "Dimension" achieved?
AverageSuccess <- c(2.28, 1.82, 1.88,1.86, 2.77)
# 1 = yes, totally achived
# 5 = not at all
# Chart should however adapt to other scales as well.

df <- data.frame(Dimension, ImportanceToPercentOfRespondents, AverageSuccess)


# ----------- Font for chart -----------

# library(extrafont)
# font_import(pattern="Open Sans Semibold")
# font_import(pattern="Open Sans")


# ----------- Chart --------------------

require(ggplot2)    
# df <- data.frame(x = Dimension, y = abs(rnorm(5)*100)
df <- data.frame(x = Dimension, y = ImportanceToPercentOfRespondents)
df$y2 <- AverageSuccess #abs(rnorm(5))


#limits of the secondary axis - adjust boundaries when needed
y2_l = 1
y2_r = 4


#transformation factor
transf_fact <- 100/(y2_r - y2_l)



# Plot
p <- ggplot(data = df,aes(x = as.factor(x), y = y)) +
  geom_col(fill = '#A60032') +
  scale_x_discrete(limits = c("Sales","Image","PR","Presentations","Observation"))+
  
  # Shift y-axis by 1 unit, apply transformation factor and reflect symmetrically w.r.t. y = 50
  geom_line(aes(y = 100 -(df$y2 - (y2_l))*transf_fact, group = 1))


#We are looking for a linear mapping from 0-100 (left axis) to 4-1 (or 5-1, 6-1), adjust if necessary
m <- lm(y~x, data.frame(x=c(0,100), y = c(y2_r, y2_l)))

p + 
  # Add second OY axis; note the transformation back (division)
  scale_y_continuous(limits = c(0,100), 
                     sec.axis = sec_axis(trans = ~ (m$coefficients[[1]] + m$coefficients[[2]]*.), 
                                         name  = "Average Success (mean)"))+
  geom_label(aes(y = 100-(df$y2-y2_l)*transf_fact, 
                 label = round(y2, 2))) +
  xlab("Dimension") + 
  ylab("Important to test persons (%)")
# theme_bw() +
# theme(text=element_text(family = "Open Sans"))

3
2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions