简体   繁体   中英

How to customize the range of values in a y-axis of a geom_bar plus geom_error bar plot

So, for my data, the default ggplot gave;

在此处输入图像描述

Now, i wish for my range of values on the y-axis to be; "0.5","1.0","1.5" to enable a better observation of the trend of the plots which seems to be between 0.8 and 1.0.

To do this, i added the code below to my plot;

scale_y_discrete(limits = c(0.5,1.5), breaks = c(0.5, 1.0, 1.5))

But instead of getting my desired result which is to visually eliminate 0 to 0.5 on the plot, i got;

在此处输入图像描述

Without a reproducible example, I've had to attempt to recreate your plot:

library(ggplot2)
library(ggpubr)

set.seed(69)
Regions <- rep(paste("Region", 1:10), each = 4)
Regions <- factor(Regions, levels = paste("Region", 1:10))
Index <- rep(c("HDI", "II", "HI", "EI"), 10)
Index <- factor(Index, levels = c("HDI", "II", "HI", "EI"))
Mean <- runif(40, .85, .95)
Upper <- Mean + 0.015
Lower <- Mean - 0.01
Upper[Index == "HI" | Index == "EI"] <- NA
Lower[Index == "HI" | Index == "EI"] <- NA

df <- data.frame(Regions, Index, Mean, Lower, Upper)

p <- ggplot(df, aes(Regions, Mean, fill = Index)) + 
  geom_col(position = "dodge", width = 0.8, colour = "#6b6f74") +
  geom_errorbar(aes(ymin = Lower, ymax = Upper), position = "dodge") +
  scale_fill_manual(values = c("#fae4ba", "#dba115", "#aba8a7", "#447ba4")) +
  theme_pubr() +
  theme(legend.position = "top") +
  labs(title = "Regional population distribution by social indexes",
       y = "Mean +- SD of Crude Rate")

p

在此处输入图像描述

And after all that, I've come to the conclusion that you were just looking for coord_cartesian :

p + coord_cartesian(ylim = c(0.75, 1.05))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM