I would like to fix the secondary axis from 0 to 1 since the probability is always range from 0 to 1. However, based on the data, if the maximum return (y) is high (as shown in the diagram below, 6%), then the scale of secondary y-axis will exceed 1 (since it depends on primary y-axis), which is not an ideal situation for presentation. How should I limit the maximum of scale for secondary y-axis?
I heard that ggplot
still not allow us to limit the scale for secondary axis, but I'm not sure whether is true or not. Is there any other ways to limit the scale for secondary y-axis so that the maximum probability show on the graph will always be 1 or less than 1 depends on the maximum return. Please note that the y shown in the code is the return.
y <- c(0.01, -0.005, 0.06)
Month <- c("Jan", "Feb", "Mar")
dtf <- data.frame(Month, y)
require(reshape)
dtf2 <- melt(dtf)
dtf2[["sign"]] = ifelse(dtf2[["value"]] >= 0, "positive", "negative")
Probability <- c(0.4,0.22,0.54)
dtf2 <- data.frame(dtf2, Probability)
dtf2 %>>% ggplot() +
geom_bar(mapping = aes(x=Month, y=value, fill = sign), stat ="identity", width = 0.75)+
geom_point(mapping = aes(x=Month, y=Probability/20-0.025), size = 2.5, color="blue")+
geom_line(mapping = aes(x=Month, y=Probability/20-0.025, group = 1), color = "blue", size = 1)+
geom_hline(yintercept=0)+
geom_text(aes(x=Month, y=value, label = paste(y * 100,"%"), vjust = ifelse(y >= 0, -0.5, 1.2)), hjust = 0.5)+
ylab("\nReturn")+
theme(axis.text.x = element_text(face = "bold", size=11),
axis.text.y = element_text(face = "bold"),
axis.title.x=element_blank(),
legend.position = "none",
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))+
theme(panel.background = element_blank(),
axis.ticks.x = element_blank()) +
theme(axis.line.y = element_line(color="black", size = 0.5))+
scale_y_continuous(labels=scales::percent, sec.axis = sec_axis(~(. + 0.025)*20, name = "Probability\n" ))+
scale_fill_manual(values = c("positive" = "black", "negative" = "red"))
I hope the maximum scale for secondary y-axis is always 1 or less than 1 if the returns are lower . Please give some advise, thanks!