【问题标题】:r ggplot x axis tick marks orderr ggplot x轴刻度线顺序
【发布时间】:2015-08-17 22:53:48
【问题描述】:

我已经看到了几个关于 x 轴标记顺序的问题,但仍然没有一个可以解决我的问题。 我正在尝试做一个密度图,显示在每个分数中按百分位分布的人,就像这样

library(dplyr); library(ggplot2); library(ggtheme)
ggplot(KA,aes(x=percentile,group=kscore,color=kscore))+
  xlab('Percentil')+ ylab('Frecuencia')+ theme_tufte()+ ggtitle("Prospectos")+
  scale_color_brewer(palette = "Greens")+geom_density(size=3)

但是 x 轴标记的顺序是 1,10,100,11,12,..,2,20,21,..,99 而不是 1,2,3,..,100 这是我想要的输出

我担心这会影响整个情节而不仅仅是标签

【问题讨论】:

  • 您的 x 变量是一个因素。您可能希望它是数字。 KA$percentile = as.numeric(as.character(KA$percentile)).
  • 添加dput(head(KA)) 有助于确认这一点
  • ...但是当您的排序明显是字母“1, 10, 100, 11, 12, ..., 2”时,几乎不需要确认。
  • 如果有 100 个级别 dput(droplevels(head(KA))) 会更好。
  • 因为 x 轴是按字母顺序排列的,您可以查看这篇文章:stackoverflow.com/questions/12774210/…

标签: r plot ggplot2


【解决方案1】:

我会将我的评论转为答案,以便将其标记为已解决:

您的 x 变量(几乎可以肯定)是一个因素。您可能希望它是数字。

KA$percentile = as.numeric(as.character(KA$percentile))

当您看到奇怪的东西时,最好检查一下您的数据。运行str(KA) 是查看其中内容的好方法。如果你只是想看课程,sapply(KA, class) 是一个不错的总结。

这是一个常见的 R 怪癖,如果您要从因子转换为数字,请使用字符,否则您可能会最终只得到级别数字:

year_fac = factor(1998:2002)
as.numeric(year_fac) # not so good
# [1] 1 2 3 4 5
as.numeric(as.character(year_fac)) # what you want
# [1] 1998 1999 2000 2001 2002

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多