【问题标题】:change x location of violin plot in ggplot2在ggplot2中更改小提琴图的x位置
【发布时间】:2018-12-10 22:44:36
【问题描述】:

我试图使用 x 中的连续变量创建小提琴图。我目前的 x 值为 0、3、5、8。当我将它们绘制成小提琴时,它们彼此间隔相等。有没有办法强制小提琴的位置基本上在 0,3,5,8?

我包含了一些示例数据和我实际上试图运行的行。

     condition movedur
 [1,]         5   0.935
 [2,]         0   1.635
 [3,]         3   0.905
 [4,]         8   0.875
 [5,]         3   1.060
 [6,]         8   1.110
 [7,]         3   1.830
 [8,]         5   1.060
 [9,]         5   1.385
[10,]         5   1.560
[11,]         0   1.335
[12,]         3   0.880
[13,]         0   1.030
[14,]         8   1.300
[15,]         3   1.230
[16,]         3   1.210
[17,]         5   1.710
[18,]         3   1.000
[19,]         0   1.365
[20,]         0   1.000

ggplot(a, aes(x = condition, y = movedur, fill = condition)) +
geom_violin()

当我运行完整的代码时,我得到了下面的图像。但是 x 轴是等间距的,而不是被值隔开。

【问题讨论】:

    标签: r ggplot2 violin-plot


    【解决方案1】:

    这是因为小提琴图旨在用于 x 轴上的分类数据,因此它只是将 condition 的不同值视为类别而不是连续轴上的值。要获得所需的结果,您可以使用complete 插入与其他轴值相对应的缺失值,如下所示。请注意,您需要插入 factor 调用以获取 ggplot2 以使用离散的 fill 比例。

    library(tidyverse)
    tbl <- structure(list(condition = c(5L, 0L, 3L, 8L, 3L, 8L, 3L, 5L, 5L, 5L, 0L, 3L, 0L, 8L, 3L, 3L, 5L, 3L, 0L, 0L), movedur = c(0.935, 1.635, 0.905, 0.875, 1.06, 1.11, 1.83, 1.06, 1.385, 1.56, 1.335, 0.88, 1.03, 1.3, 1.23, 1.21, 1.71, 1, 1.365, 1)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(cols = list(condition = structure(list(), class = c("collector_integer", "collector")), movedur = structure(list(), class = c("collector_double", "collector"))), default = structure(list(), class = c("collector_guess", "collector"))), class = "col_spec"))
    
    tbl %>%
      complete(condition = 0:8) %>%
      ggplot() +
      geom_violin(aes(x = condition, y = movedur, fill = factor(condition)))
    #> Warning: Removed 5 rows containing non-finite values (stat_ydensity).
    

    reprex package (v0.2.0) 于 2018 年 7 月 2 日创建。

    【讨论】:

      【解决方案2】:

      如果您将 condition 变量保留为 x 轴的整数/数字,但将其用作 fill 的因子,您可以获得所需的绘图。

      请注意,您提供的数据集示例已经将 condition 作为整数,但如果它是一个因素并且您想要转换它,您可以这样做

      a$condition = as.numeric(as.character(a$condition))

      我在scale_x_continuous() 中添加breaks 以使休息时间看起来不错。

      ggplot(a, aes(x = condition, y = movedur, fill = factor(condition))) +
           geom_violin() +
           scale_x_continuous(breaks = c(0, 3, 5, 8) )
      

      【讨论】:

        猜你喜欢
        • 2021-06-15
        • 2017-08-11
        • 1970-01-01
        • 2019-01-21
        • 2021-12-23
        • 2018-05-19
        • 2018-01-15
        • 2016-06-13
        • 1970-01-01
        相关资源
        最近更新 更多