简体   繁体   中英

How to fix y-axis from negative to positive values in ggplot line plot

I have the following code

library(tidyverse)

dat <- structure(list(gene = c("Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", 
"Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", 
"Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr", 
"Ahr", "Ahr", "Ahr", "Ahr", "Ahr", "Ahr"), ct = c("A", 
"A", "A", "A", "A", "A", 
"B", "B", "B", 
"B", "B", "B", 
"C", "C", "C", "C", "C", 
"C", "D ", "D ", "D ", 
"D ", "D ", "D ", "E", 
"E", "E", "E", "E", "E"), tc = c("CONTROL", 
"DAY03", "DAY06", "DAY09", "DAY12", "DAY15", "CONTROL", "DAY03", 
"DAY06", "DAY09", "DAY12", "DAY15", "CONTROL", "DAY03", "DAY06", 
"DAY09", "DAY12", "DAY15", "CONTROL", "DAY03", "DAY06", "DAY09", 
"DAY12", "DAY15", "CONTROL", "DAY03", "DAY06", "DAY09", "DAY12", 
"DAY15"), zs = c(-0.408248, -0.408248, -0.408248, -0.408248, 
2.041241, -0.408248, -0.408248, -0.408248, -0.408248, -0.408248, 
-0.408248, 2.041241, -0.908633, 0.996489, 0.732923, -0.908633, 
0.996489, -0.908633, -0.408248, 2.041241, -0.408248, -0.408248, 
-0.408248, -0.408248, -0.408248, -0.408248, -0.408248, -0.408248, 
2.041241, -0.408248)), row.names = c(NA, -30L), class = c("tbl_df", 
"tbl", "data.frame"))


zslp <- ggplot(dat, aes(x = tc, y = zs, group = 1)) +
  geom_line() +
  # ylim(c(-2, 2)) + # to be uncomment
  facet_wrap(~ct) +
  theme_bw() + 
  theme(axis.text.x=element_text(angle = 90, hjust = 1, vjust = 0.5)) +
  xlab("") 

zslp

Which produces this plot:

在此处输入图片说明

Note that the y-axis range from -1 to 2. What I want to do is to fix it from -2 to 2.

So I uncommented this line:

ylim(c(-2, 2)) +

But the plot it produces is this:

在此处输入图片说明

Note that the A, B, D, E panel is flat. How can I resolve the problem?

Use coord_cartesian instead of ylim

zslp <- ggplot(dat, aes(x = tc, y = zs, group = 1)) +
  geom_line() +
  coord_cartesian(ylim=c(-2,2)) +
  facet_wrap(~ct) +
  theme_bw() + 
  theme(axis.text.x=element_text(angle = 90, hjust = 1, vjust = 0.5)) +
  xlab("") 

zslp

The trick is if you use ylim , ggplot will ignore all values that are not between the limits (and you do have some values above 2). With coord_cartesian these values are plotted anyway

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