如何在geom_bar和geom_error条形图的y轴上自定义值的范围

时间:2020-06-22 21:24:22

标签: r ggplot2 data-visualization

因此,对于我的数据,默认的ggplot给出了;

enter image description here

现在,我希望我在y轴上的值范围为; “ 0.5”,“ 1.0”,“ 1.5”,以便更好地观察似乎在0.8到1.0之间的曲线趋势。

为此,我将以下代码添加到我的绘图中;

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

但是我没有得到我想要的结果,即在视觉上消除了0到0.5,而是得到了

enter image description here

1 个答案:

答案 0 :(得分:0)

没有可复制的示例,我不得不尝试重新创建您的剧情:

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

enter image description here

毕竟,我得出的结论是,您只是在寻找coord_cartesian

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

enter image description here