首页 > 解决方案 > 命名数字向量的 geom_bar

问题描述

我正在尝试做一个在基本 R 图中非常容易的简单事情,但出于多功能性的原因,我想使用 ggplot 来代替,但我找不到最好的方法。

我有一个 PCA 特征值的命名数字向量:

nums <- c(2.491301e-01, 6.591505e-02, 4.615435e-02, 3.723229e-02, 2.124809e-02,
          1.662227e-02, 1.476976e-02, 1.297296e-02, 1.053972e-02, 6.665518e-03,
           5.040257e-03, 4.258138e-03, 2.766567e-03, 2.612342e-03, 1.504883e-03,
           1.387214e-03, 1.037458e-03, 7.814771e-04, 4.749074e-04, 4.263183e-04,
           2.812258e-04, 2.188441e-04, 1.382420e-04, 8.760467e-05, 5.336446e-05,
           1.475674e-05, 9.216328e-06)


names(nums) <- c(  "PC1"  ,"PC2" , "PC3" , "PC4" , "PC5" , "PC6" , "PC7" , "PC8" , "PC9" , "PC10",
                   "PC11", "PC12", "PC13", "PC14", "PC15", "PC16", "PC17", "PC18", "PC19", "PC20",
                   "PC21", "PC22", "PC23", "PC24", "PC25", "PC26", "PC27")

在基础 R 中,我可以轻松地制作这些值的标记条形图:

barplot(nums, main = "Eigenvalues", col = "grey", las = 2)
abline(h = mean(nums), col = "red3", lwd = 2)
legend("topright", "Average eigenvalue",
       lwd = 2, col = "red3" )

但是我在ggplot中很容易做到这一点。到目前为止,我想出的最好的是:

nums %>% 
  data.frame() %>%
  ggplot(aes(names(nums),nums)) + 
  geom_bar(stat="identity",fill="grey",color="black") +
  geom_hline(yintercept = mean(nums))+
  theme_classic() +
  theme(axis.text.x = element_text(angle=90),
        axis.title = element_blank(),
        plot.title = element_text(hjust=.5))+
  labs(title="Eigenvalues")

但这使它们令人讨厌地失序。有没有一种不烦人的方法来快速探索情节?这是基础 R 绘图优越的罕见时期之一吗?

标签: rggplot2pcaeigenvalue

解决方案


名称正在幕后转换为因子,这意味着默认情况下,您的名称将在因子转换中按字母顺序排序。您只需要通过将名称作为一个因素并声明级别的顺序来明确所需的顺序。

另外需要注意的两点是geom_barwithstat = "identity"可以替换为geom_col,并且在 ggplot 中绘图之前从变量创建数据框通常更容易。

library(ggplot2)
library(dplyr)

data.frame(names = factor(names(nums), levels = names(nums)), nums) %>%
  ggplot(aes(names, nums)) + 
  geom_col() +
  geom_hline(yintercept = mean(nums)) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 90),
        axis.title  = element_blank(),
        plot.title  = element_text(hjust = 0.5)) +
  labs(title="Eigenvalues")

reprex 包于 2020-07-01 创建(v0.3.0)


推荐阅读