【问题标题】:ggplot axis custom order with duplicate labels带有重复标签的ggplot轴自定义顺序
【发布时间】:2017-05-12 18:09:21
【问题描述】:
set.seed(357)
x <- data.frame(name = sample(letters, 10), val = runif(10), stringsAsFactors = F)
x[c(2,6),"name"] <- c("k","k")
ggplot(x, aes(x = name, y = val)) + theme_bw() + geom_bar(stat = "identity")

如何以与 x$name 相同的顺序绘制轴? (是的,k 是重复的,我希望它像这个轴一样显示在图中:c k g f o k s v t q)

过去我曾经这样做过:

x$name <- factor(x$name, levels = x$name[order(x$val)], ordered = T)

wich 不再起作用了,这要归功于: http://r.789695.n4.nabble.com/factors-with-non-unique-quot-duplicated-quot-levels-have-been-deprecated-since-2009-are-more-depreca-td4721481.html

这不是重复的:ggplot: order of factors with duplicate levels 他的数据结构完全不同。

另外,我尝试在 x_scale_discrete 中设置限制。没用。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个...

    x$name2 <- 1:nrow(x)
    ggplot(x, aes(x = factor(name2), y = val)) + theme_bw() + geom_bar(stat = "identity") + 
                 scale_x_discrete(labels=x$name)
    

    【讨论】:

    • 我尝试使用时间序列数据进行此操作,其中同一日期在 x 轴上重复多次,此解决方案只是将重复值堆叠为一个。不会以某种方式分别显示它们。
    • @samsamara 没有看到您的数据很难判断。您最好将此作为一个单独的问题提出,并附上一个可重复的示例并清楚地描述您要达到的目标。
    • 不用担心。我发布了一个问题并得到了答案。只是我需要在 geom 对象中使用 'position_dodge()'。 stackoverflow.com/questions/65316274/…
    【解决方案2】:

    其实只需添加如下设置xlab(x$name)

    ggplot(x, aes(x = name, y = val)) + theme_bw() + geom_bar(stat = "identity") + xlab(x$name)
    

    【讨论】:

    • 对不起,不工作。 ggplot2 自动认为两个 k 属于一起并将它们放在一个栏中。
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2012-09-20
    • 2019-04-03
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2023-03-06
    • 2018-11-25
    相关资源
    最近更新 更多