代码之家  ›  专栏  ›  技术社区  ›  Johnny Banana

带有geom_文本的散点图-显示标签的子样本

  •  0
  • Johnny Banana  · 技术社区  · 8 年前

    我正在用ggplot2运行以下R代码

    library(ggplot2)
    
    ggplot(result, aes(x=X2015, y=CPI.2015, color=Region)) + 
        geom_point(size=6, alpha=0.6)  +
        geom_text(aes(label=Country), size=3,color = "black")
       #scale_x_discrete(breaks=seq(0,1000, 200))
    

    然而,我遇到了以下问题:

    result plot

    1. x轴完全无法读取。我的代码中有这一行(注释掉)如上所述,但我得到了这个“离散值到连续尺度”的错误。

    2. 为了便于阅读,我不想显示所有的名字,只是其中的一些。这真的可能吗?

    1 回复  |  直到 8 年前
        1
  •  0
  •   pogibas    8 年前

    如果没有原始数据,很难调整参数,但请尝试以下方法:

    转换 X2015 到数字:

    result$X2015 <- as.numeric(result$X2015)
    

    随机抽样标签 geom_text :

    # Number of labels to show
    nOfLabels <- 10
    result$Country2 <- ifelse(1:nrow(result) %in% sample(1:nrow(result), nOfLabels), 
                              result$Country, "")
    

    在这里,我随机抽取了10个国家,其余的返回空字符串 "" .

    并绘制您的 result 使用:

    library(ggplot2)
    ggplot(result, aes(X2015, CPI.2015, color = Region)) + 
        geom_point(size = 6, alpha = 0.6)  +
        geom_text(aes(label = Country2), size = 3,color = "black") +
        scale_x_discrete(breaks = seq(0, 1000, 200))
    
    推荐文章