Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206673

Ggplot() in R - Rescaling Primary and Secondary Axes

$
0
0

I have some code that will draw a nice "combo" graph with separate primary and secondary axes (which is what I need for a particular application). A simple example here:

library(tidyverse)

df <- data.frame(star_sign = c("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"),
                 weight = c(50, 70, 60, 40, 45, 78, 42, 22, 28, 49, 50, 31),
                 mean = c(1.1, 1.2, 1.4, 1.3, 1.8, 1.6, 1.4, 1.3, 1.2, 1.1, 1.5, 1.3))

lvls = c("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces")

a <- 0
b <- 0.01
primary_y_min <- -1
primary_y_max <- 2

df %>% 
  mutate(star_sign = as.numeric(factor(star_sign, levels = lvls))) %>% 
  ggplot(aes(star_sign)) + 
  geom_line(aes(y = mean), color = "red") + 
  geom_col(aes(y = (weight + a) * b), width = 0.5, fill = "blue") + 
  scale_y_continuous("values", limits = c(primary_y_min, primary_y_max), sec.axis = sec_axis(~ ./b - a, name = "weight")) +  
  scale_x_continuous("X title", breaks = c(1:12), labels = lvls) 

Tweaking the values of a, b, primary_y_min, and primary_y_max gives me some control over the axes (the primary axis in particular). But it's not quite giving me what I need. I'd like to be able to choose:

  • Primary axis: min and max y

  • Secondary axis: max y (min y will always be 0)

Is there a way to do this? I would hope it was fairly easy (!) But my knowledge of ggplot2 is minimal so I'm not sure how to go about this.


Viewing all articles
Browse latest Browse all 206673

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>