Reputation: 397
having scanned everything I can find on scale_y_continuous is there are way to achieve the following:
Dynamic y axis for survey data where limits change for % and mean result. P is a % value and the axis needs to be set at 0 - 100 M is a mean value and needs to be set at 1 - 6
This would be really easy if all values were in the same plot; however I have two graphs together in a ggarrange and the second graph has values that are less than the first and the bars are not aligned.
library(ggplot2)
df <- data.frame(dose=c("D0.5", "D1", "D2"),
P = c(42, 98, 77.5),
M = c(2,3.4,5.5)
)
ggplot(data=df, aes(x=dose, y=P)) +
geom_bar(stat="identity")
Is there a way to set scale_y_continuous for P to c(0,100), and for M c(0.6).
Upvotes: 0
Views: 731
Reputation: 388817
To get one plot based on user input choice we can do :
library(ggplot2)
choice = 'P'
if(choice == 'P') {
p1 <- ggplot(data=df, aes(x=dose, y=P)) + geom_col() +
scale_y_continuous(limits = c(0, 100))
} else {
p1 <- ggplot(data=df, aes(x=dose, y=M)) + geom_col() +
scale_y_continuous(limits = c(0, 6))
}
p1
To get both the plots together :
You can set limits
for individual plots using scale_y_continuous
before combining them in ggarrange
.
p1 <- ggplot(data=df, aes(x=dose, y=P)) + geom_col() +
scale_y_continuous(limits = c(0, 100))
p2 <- ggplot(data=df, aes(x=dose, y=M)) + geom_col() +
scale_y_continuous(limits = c(0, 6))
ggpubr::ggarrange(p1, p2)
However, you can also consder using facets with different y-axis :
df %>%
tidyr::pivot_longer(cols = c(P, M)) %>%
ggplot() + aes(dose, value) + geom_col() +
facet_wrap(.~name, scales = "free_y")
Upvotes: 2