【问题标题】:Ordering categorical variables with ggplot stacked barplots使用 ggplot 堆积条形图对分类变量进行排序
【发布时间】:2018-03-23 00:10:39
【问题描述】:

我有一个包含 252 个 obs 的 8 个变量的数据框 tbl。

> str(CE0008)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   252 obs. of  8 variables:
 $ Period start time: POSIXct, format: "2018-02-28" "2018-02-28" "2018-02-28" "2018-02-28" ...
 $ WBTS name        : chr  "CE0008" "CE0008" "CE0008" "CE0008" ...
 $ WBTS ID          : num  27 27 27 27 27 27 27 27 27 27 ...
 $ WCEL name        : chr  "CE0008U09C3" "CE0008U21B1" "CE0008U21B3" "CE0008U21C2" ...
 $ WCEL ID          : num  33 2 22 13 32 3 23 1 11 31 ...
 $ PRACHDelayRange  : num  4 4 4 4 4 4 4 4 4 4 ...
 $ class            : Ord.factor w/ 21 levels "Class 0"<"Class 1"<..: 1 1 1 1 1 1 1 1 1 1 ...
 $ count            : num  22177 37507 37580 24066 6029 ...

我希望生成一个条形图,其中 x 轴包含类变量,其中类变量从 Class 0 到 Class 20 排序。条形的高度由 count 变量给出,条形由 WCEL 名称着色.

从我的数据框 tbl 的 str 中,类变量是一个 ord。因素,但由于某种原因,当我绘制数据时,订单不会延续,并且类似地通过“WCEL 名称”填充颜色。任何指针将不胜感激。

ggplot(data = CE0008, aes(x = class, y = count, fill = 'WCEL name')) + geom_col()

【问题讨论】:

  • 我认为 ggplot2 不能使用有序因子。因此,您的解决方案要么是 unclass,然后将变量转换为常规因子(按您想要的顺序设置级别),或者使用 ggplot2::scale_x_discrete() 设置顺序。见this SO question
  • 看看here

标签: r ggplot2


【解决方案1】:

data$class

你的 ggplot 调用在这里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多