首页 > 解决方案 > ggpubr ggbarplot 用奇异的 xvalues 绘制

问题描述

我使用下面的 CSV 有以下代码

library(ggpubr)
library(ggsci)
df = read.csv2("file.csv", row.names=1)
# Copy df
df2 = df
# Convert the cyl variable to a factor
df2$perc <- as.factor(df2$perc)
# Add the name colums
df2$name <- rownames(df)
ggbarplot(df2, x = "name", y = "perc",
          fill = "role",               # change fill color by cyl
          color = "white",            # Set bar border colors to white
          palette = "npg",            # jco journal color palett. see ?ggpar
          sort.val = "asc",          # Sort the value in dscending order
          sort.by.groups = FALSE,     # Don't sort inside each group
          x.text.angle = 0,           # Rotate vertically x axis texts
          rotate = TRUE,
          label = TRUE, label.pos = "out",
          #label = TRUE, lab.pos = "in", lab.col = "white",
          width = 0.5
)

CSV是:

genes;perc;role
GATA-3;7,9;confirmed in this cancer
CCDC74A;6,8;prognostic in this cancer
LINC00621;6,1;none
POLRMTP1;4,1;none
IGF2BP3;3,2;confirmed in this cancer

产生了这个情节

在此处输入图像描述

有两件事我在这里没有得到:

1) 为什么每个柱的 x 轴刻度对应于绘制的实际值?我的意思是为什么 x 轴不是从 0 到 8,我认为应该如此。我希望我解释正确。

2) 标签值似乎与 y 厚度不一致。我在这里错过了一个选项吗?

标签: rggplot2ggpubr

解决方案


老实说,我可能不会ggpubr在这里使用。保持 ggplot 语法通常更安全。并且可以说代码更少......(另外,在这种情况下不要使用因子,正如用户 teunbrand 评论的那样)

水平条的两个不错的选择:

library(tidyverse)
library(ggstance)
library(ggsci)

选项 1 - 使用 coord_flip

ggplot(df2, aes(fct_reorder(genes, perc), perc, fill = role)) +
  geom_col() +
  geom_text(aes(label = perc), hjust = 0) +
  scale_fill_npg() +
  coord_flip(ylim = c(0,100)) +
  theme_classic() +
  theme(legend.position = 'top') +
  labs(x = 'gene', y = 'percent')

选项 2 - 使用 ggstance 包 我更喜欢选项 2,因为使用 ggstance 可以更灵活地与其他地块组合

ggplot(df2, aes(perc, fct_reorder(genes, perc), fill = role)) +
  geom_colh() +
  geom_text(aes(label = perc), hjust = 0)+
  scale_fill_npg() +
  coord_cartesian(xlim = c(0,100)) +
  theme_classic() +
  theme(legend.position = 'top')+
  labs(x = 'gene', y = 'percent')

reprex 包(v0.3.0)于 2020 年 3 月 27 日创建

数据

df2 <- read_delim("genes;perc;role
GATA-3;7,9;confirmed in this cancer
CCDC74A;6,8;prognostic in this cancer
LINC00621;6,1;none
POLRMTP1;4,1;none
IGF2BP3;3,2;confirmed in this cancer", ";") %>% rownames_to_column("name")

推荐阅读