Reputation: 837
i have the following plot in ggplot2
but I'm not too happy with how the secondary y axis is scaled cause the grey line looks fairly flat.
I would prefer to create a scale for the secondary y axis and the grey line with a range of only 1.75 to 2.25 so that I can see the movements a bit better. Any advice on how to do this?
library(tidyverse)
reserves_level <- structure(list(Date = structure(c(18291, 18321, 18351, 18382,
18412, 18443, 18473, 18504, 18535, 18565, 18596, 18626, 18657,
18291, 18321, 18351, 18382, 18412, 18443, 18473, 18504, 18535,
18565, 18596, 18626, 18657), class = "Date"), Key = c("Reserves (NAD)",
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)",
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)",
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)",
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)",
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)",
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)",
"Reserves (USD)"), Value = c(30.96107351507, 32.16872169411,
32.97394333811, 35.6594389906, 32.944455576, 31.75897192528,
35.3995709836, 33.3870647566, 32.66579275848, 34.35383925875,
29.92587, 31.7517, 33.35816, 2.06261398712043, 2.05295138288458,
1.84674175243683, 1.92451004045528, 1.87739090357876, 1.83355302380232,
2.08125035179437, 1.97135496109494, 1.95207290341642, 2.11488932754343,
1.94197, 2.10318, 2.20185)), row.names = c(NA, -26L), class = c("tbl_df",
"tbl", "data.frame"))
ggplot() +
geom_col(data = subset(reserves_level, Key %in% c("Reserves (NAD)")),
mapping = aes(x = Date, y = Value, fill = Key),
position = position_dodge()) +
geom_line(data = subset(reserves_level, Key == "Reserves (USD)"),
mapping = aes(x = Date, y = Value*15, group = Key, color = Key),
size = 2) +
scale_fill_manual(values = c('#7c3042','#c7af76')) +
scale_color_manual(values = c('grey')) +
theme_bw() +
scale_y_continuous(sec.axis= sec_axis(~./15, name="Reserves (USD)", breaks = seq(0,2.5, by = 0.25)))
Upvotes: 0
Views: 206
Reputation: 98
May be this can help you
ylim.p <- c(0, 30)
ylim.s <- c(1.75, 2.25)
b <- diff(ylim.p)/diff(ylim.s)
a <- b*(ylim.p[1] - ylim.s[1])
ggplot() +
geom_col(data = subset(reserves_level, Key %in% c("Reserves (NAD)")),
mapping = aes(x = Date, y = Value, fill = Key),
position = position_dodge()) +
geom_line(data = subset(reserves_level, Key == "Reserves (USD)"),
mapping = aes(x = Date, y = (Value*b)+a, group = Key, color = Key),
size = 2) +
scale_fill_manual(values = c('#7c3042','#c7af76')) +
scale_color_manual(values = c('grey')) +
theme_bw() +
scale_y_continuous(sec.axis= sec_axis(~(. - a)/b, name="Reserves (USD)", breaks = seq(1.75,2.5, by = 0.25)))
Upvotes: 1