【问题标题】:ggplot2 defined Y-axis and boxplotggplot2 定义了 Y 轴和箱线图
【发布时间】:2019-09-02 22:50:04
【问题描述】:

我想使用 ggplot2/facet_wrap 将 6 个基因的 PCR 值绘制成多个条形图。 (1) 绘图的 y 轴显示特定值,小数位较长时看起来很尴尬。 (2) 当我使用 facet_wrap 时,箱形图不可见。

代码:

PCR <- read_excel("2019-09 qPCR.xlsx", 1)
PCRvar <- melt(data = PCR, id.vars = 1)   #listed the variables 
ggplot(data = PCRvar, mapping = aes(x = Group, y = value, fill = Group)) + 
facet_wrap(~variable) + 
geom_boxplot()

文件:Excel、绘图 http://ge.tt/5yTvCtx2

问题:

(1) 我只想显示特定值。我们能否定义 y 轴范围和区间(示例范围:-5 到 +5,区间=0.5)?

(2) 箱形图不可见?谁能提供解决方案。

【问题讨论】:

  • 看起来您的 y 轴值是类型因子,而不是数字。请注意,有些值包含字符 - 默认情况下,这些值将作为因子读取。这解释了轴标签的外观和箱线图问题。
  • 非常感谢您的宝贵时间。

标签: r ggplot2


【解决方案1】:

有关 y 轴范围,请参阅 ?ylim?scale_y_continuous

您的下一个问题是 reshape2::melt() 使用不正确,因此您在 value 列中有包含字符的值:

reshape2::melt(PCR, id.vars = 1) %>% str()

'data.frame':   42 obs. of  3 variables:
 $ Group   : chr  "Basal" "Basal" "Basal" "TGFb" ...
 $ variable: Factor w/ 7 levels "Treatment","P14",..: 1 1 1 1 1 1 2 2 2 2 ...
 $ value   : chr  "Basal_1" "Basal_2" "Basal_3" "TGFb_1" ...

我建议改为tidyr::gather()

library(tidyr)
library(ggplot2)

PCR %>% gather(Var, Val, -Group, -Treatment) %>% str()

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   36 obs. of  4 variables:
 $ Group    : chr  "Basal" "Basal" "Basal" "TGFb" ...
 $ Treatment: chr  "Basal_1" "Basal_2" "Basal_3" "TGFb_1" ...
 $ Var      : chr  "P14" "P14" "P14" "P14" ...
 $ Val      : num  0 0 0 3.02 2.87 ...

Boxplot 现在应该给出预期的结果:

PCR %>% 
  gather(Var, Val, -Group, -Treatment) %>% 
  ggplot(mapping = aes(x = Group, y = Val, fill = Group)) + 
  facet_wrap(~Var) + 
  geom_boxplot()

但是:考虑到值的数量很少以及许多控件 = 0 的事实,我建议显示单个观察结果而不是使用箱线图:

PCR %>% 
  gather(Var, Val, -Group, -Treatment) %>% 
  ggplot(mapping = aes(x = Group, y = Val, color = Group)) + 
  facet_wrap(~Var) + 
  geom_jitter(width = 0.2)

【讨论】:

  • 非常感谢您的快速回答#neilfws。我是生物学家。正在学习 R 并在周末努力解决它。爱和非常感谢:)
  • 不客气。我也是生物学家,很久以前学习R :) 坚持下去,值得努力。
  • 太好了,谢谢。
  • 另一个问题是,在我向表格添加更多条件以绘制单个箱线图后,x 轴与数据框中的顺序不同。代码:PCR % ggplot(mapping = aes(x = Group, y = P14, fill = Group)) + geom_boxplot().
  • 我从 stackoverflow 较早的帖子中尝试了不同的解决方案,例如 aes(x=reorder(Group, P14), y=P14, fill=Group)) 或 aes(fct_infreq(factor(Group)), y =P14, fill=Group)),但他们按字母顺序对 x 轴进行了排序。您能否建议获得 excel 中的预期顺序:Basal、ATII-100、ATII-200、TGFb、TNFa。
猜你喜欢
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 2023-03-10
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
相关资源
最近更新 更多