【问题标题】:Make x-axis appear in a particular order in ggplot使 x 轴在 ggplot 中以特定顺序出现
【发布时间】:2023-02-03 15:53:16
【问题描述】:

我有一个数据集:

data <- c('real','real','real','real','real','pred','pred','pred','pred','pred','real','real','real','real','pred','pred','pred','pred')
threshold <- c('>=1','>=2','>=3','>=4','>=101','>=1','>=2','>=3','>=4','>=101','>=1','>=2','>=3','>=4','>=1','>=2','>=3','>=4')
accuracy <- c(63.4,64.4,65.1,64.3,65.4,62.1,63.6,64.1,65.4,64.8,62.2,63.3,64.4,65.6,63.1,63.8,64.6,65.1)
types<-c('morning','morning','morning','morning','morning','morning','morning','morning','morning','morning','evening','evening','evening','evening','evening','evening','evening','evening')

df <- data.frame(data,threshold,accuracy,types)

我想将“数据”列分别绘制为早上和晚上的堆叠条形图。所以我使用面包裹。我的绘图代码是:


ggplot(df, aes(x = threshold, y = accuracy)) + geom_bar(aes(fill = data), stat = "identity", color = "white",position = position_dodge(0.9))+
  facet_wrap(~types) + 
  fill_palette("jco")

我得到的情节看起来像:

但是,如您所见,阈值的顺序被打乱了。我希望早上的订单看起来像:

'>=1','>=2','>=3','>=4','>=101'

晚上的顺序应该是:

'>=1','>=2','>=3','>=4'

所以我有三个问题:

  1. 如何使用我的代码执行命令?

    2 同样在晚上,我不应该得到 '>=101' 那么我怎样才能从情节中删除它。

    1. 有没有办法使背景变白但保留网格。

    2. 在一个稍微不相关的注释中,你能指出一种可能比这看起来稍微好一点的图表类型吗?我是可视化方面的新手,所以我还在学习。

    见解将不胜感激。

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    您可以设置 threshold 的顺序来重新排序 x 轴。

    然后在facet_wrap中添加scales = 'free'删除evening中的&gt;=101

    添加theme_bw() 使背景变白。

    df %>%
      mutate(threshold = factor(threshold, levels = c('>=1','>=2','>=3','>=4','>=101'))) %>%
      ggplot(aes(x = threshold, y = accuracy)) + geom_bar(aes(fill = data), stat = "identity", color = "white",position = position_dodge(0.9))+
      facet_wrap(~types, scales = 'free') +
      theme_bw() + 
      fill_palette("jco")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 2021-11-30
      • 2014-09-24
      相关资源
      最近更新 更多