简体   繁体   English

如何在ggplot线图中将y轴从负值固定为正值

[英]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.注意y轴范围从-1到2。我想要做的是将它从-2修复到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.请注意,A、B、D、E 面板是平坦的。 How can I resolve the problem?我该如何解决问题?

Use coord_cartesian instead of ylim使用coord_cartesian而不是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).诀窍是,如果您使用ylim , ggplot 将忽略不在限制之间的所有值(并且您确实有一些大于 2 的值)。 With coord_cartesian these values are plotted anyway无论如何,使用coord_cartesian绘制这些值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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