Home > Software design >  ggplot2 with 2 y-axis in R: error term about discrete values
ggplot2 with 2 y-axis in R: error term about discrete values

Time:11-24

I'm trying to build a graph with two y-axis, showing the development of homicides and share of national wealth of the bottom 50% in Sierra Leone between 2004 and 2015. I'm quite familiar with ggplot in simpler circumstances, now I'm struggeling. There have been some posts regarding this topic, but the approach via scale_y_continuous for the second y-axis won't work for me. I keep getting this error: Error: Discrete value supplied to continuous scale

I've checked my dataframe for discrete values via is.discrete and there are none. Does anyone have some advise for me? Thanks in advance

year <- c(2004, 2005, 2006, 2007, 2008, 
          2009, 2010, 2011, 2012, 2015)
share <- c(0.0434, 0.0446, 0.0452, 0.0458, 
           0.0466, 0.0472, 0.0475, 0.0479, 0.0475, 0.0465)
p100kp <- c(2.0611, 1.7536, 1.7326, 2.2372, 
            2.9999, 2.5188, 2.5407, 2.8492, 1.6834, 1.7290)

df <- data.frame(year, share, p100kp)


PP1 <- ggplot(df, aes(x = year, y = p100kp))  
  geom_line(aes(color = "Homicides per 100K population"))  
  geom_line(aes(y = share, color = "Share of national wealth"))  
  scale_x_continuous(breaks = seq(2004, 2015))  
  scale_y_continuous(sec.axis = sec_axis(~.*scale, name="Share"))  
  labs(x = "Year", y = "Homicides per 100K population", color = "")  
  scale_color_manual(values = c("orange2", "gray30"))

print(PP1)

CodePudding user response:

The following is a fully reproducible example. If you copy-paste this code you should get the same result:

df <- data.frame(year = c(2004, 2005, 2006, 2007, 2008, 2009, 2010, 
2011, 2012, 2015), share = c(0.0434, 0.0446, 0.0452, 0.0458, 
0.0466, 0.0472, 0.0475, 0.0479, 0.0475, 0.0465), p100kp = c(2.0611, 
1.7536, 1.7326, 2.2372, 2.9999, 2.5188, 2.5407, 2.8492, 1.6834, 
1.729))

library(ggplot2)

scale <- 0.02

ggplot(df, aes(x = year, y = p100kp))  
  geom_line(aes(color = "Homicides per 100K population"))  
  geom_line(aes(y = share/scale, color = "Share of national wealth"))  
  scale_x_continuous(breaks = seq(2004, 2015))  
  scale_y_continuous(sec.axis = sec_axis(~.*scale, name="Share"))  
  labs(x = "Year", y = "Homicides per 100K population", color = "")  
  scale_color_manual(values = c("orange2", "gray30"))

enter image description here

Created on 2022-11-23 with enter image description here

  • Related