【问题标题】:keep data order for geom_bar() ggplot2 in R在 R 中保持 geom_bar() ggplot2 的数据顺序
【发布时间】:2021-08-21 07:17:41
【问题描述】:

我创建了以下数据框:

    condition <- rep(c("Pretreatment", "Normal"), 4)
    value <- c( "3.6", "0.2", "5.6", "0.2", "7.4", "0.2", "8.8", "0.2")
    time<- c("5","5", "10", "10", "15","15", "20", "20")
    domedata <- data.frame(time, condition, value)

我想按顺序保持 x 中的时间条,因为它告诉我们时间 5 分钟、10 分钟、15 分钟、20 分钟。 ggplot 在最后绘制我的 5 分钟。我正在这样做:

    ggplot(domedata, aes(fct_infreq(time), fill=condition, x=time, y=value)) +
           geom_bar(position="dodge", stat = "identity") 

【问题讨论】:

  • 将时间转换为数字或尝试使用forcats::fct_inorder

标签: r dataframe ggplot2 bar-chart geom-bar


【解决方案1】:

看来您正在传递给x 美学,所以最后一个将覆盖第一个。 下面我删除了美学的第一个参数是多余的,我使用了fct_inorder,@stefan 也评论了

condition <- rep(c("Pretreatment", "Normal"), 4)
value <- c( "3.6", "0.2", "5.6", "0.2", "7.4", "0.2", "8.8", "0.2")
time <- c("5","5", "10", "10", "15","15", "20", "20")
domedata <- data.frame(time, condition, value)

ggplot(domedata, aes(fill=condition, x=fct_inorder(time), y=value)) +
  geom_bar(position="dodge", stat = "identity") 

但请注意,由于您的值是字符串,因此 y 轴的比例有点奇怪,我建议您通过删除引号将值和时间都转换为数字数据类型,就像这样

library(tidyverse)

condition <- rep(c("Pretreatment", "Normal"), 4)
value <- c(3.6, 0.2, 5.6, 0.2, 7.4, 0.2, 8.8, 0.2)
time <- c(5,5, 10, 10, 15,15, 20, 20)
domedata <- data.frame(time, condition, value)

ggplot(domedata, aes(fill=condition, x=time, y=value)) +
  geom_bar(position="dodge", stat = "identity") 

这样情节就不会那么误导了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多