【问题标题】:Grouped bar chart with time duration on y axis in r在 r 中的 y 轴上具有持续时间的分组条形图
【发布时间】:2016-07-01 19:01:24
【问题描述】:

我有类似的数据,

column1 <- c(rep("ab", 3), rep("cd", 3), rep("ef", 3))
column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
column3 <- c("10:10:00", "01:15:10", "00:00:20", "01:20:40", "05:20:55", "10:00:00", "02:00:30", "03:23:55", "10:01:40")

我需要使用 ggplot 为这些数据绘制分组条形图。我在 rscript 下面试过了。

d <- data.frame(column1=column1, column2=column2, column3=column3)

require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(position=position_dodge(),stat="identity")

它给出了类似的情节,

由于以下问题而看起来不对,

  1. 列顺序一致
  2. Y 轴上的时间不一致。 (范围错误)。

但如果我尝试以下数据,

column1 <- c(rep("ab", 3), rep("cd", 3), rep("ef", 3))
column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
column3 <- c(10, 15, 20, 80, 95, 10, 30, 55, 80)

d <- data.frame(column1=column1, column2=column2, column3=column3)
require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(position=position_dodge(),stat="identity")

它会产生类似的图形,

看起来很完美。 我在这里看到的问题是它适用于整数,但不适用于时间数据类型。我试图玩它,但无法成功。任何人都可以帮我创建正确的图表,或者请建议是否需要其他方法?

提前致谢。

【问题讨论】:

  • 以分钟为单位的 Y 轴是否足够,或者您想要小时 + 分钟?即你想要“01:20:00”而不是“80”吗?
  • 另外,column3 是否包含特定的时间或持续时间?
  • 您的时间只是字符串/因素,而不是实际时间。您需要使用时间类来按比例评估它们,例如chron::timeslubridate 之一(可能durationinterval 介于两个日期时间之间)。
  • 我们必须假设您搜索了“ggplot 持续时间”。您能否详细说明为什么前两次点击在这里没有帮助。

标签: r ggplot2 bar-chart


【解决方案1】:

此解决方案转换假定 column3 是一个持续时间,并将其转换为 Duration 类,正如@alistaire 建议的那样。让标签定期显示也可能需要进行一些修改,但这应该很容易。

library(ggplot2)

column1 <- c(rep("ab", 3), rep("cd", 3), rep("ef", 3))
column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
column3 <- c("10:10:00", "01:15:10", "00:00:20", "01:20:40", "05:20:55", 
    "10:00:00", "02:00:30", "03:23:55", "10:01:40")

d <- data.frame(column1=column1, column2=column2, column3=column3)

library(lubridate)

# convert to a duration 
c3 <- lubridate::hms(column3)
c3 <- lubridate::duration(hour = hour(c3), minute = minute(c3), 
    second = second(c3))

# convert to numeric to plot
d$c3 <- as.numeric(c3)

# labeling funtion to convert from numeric back to the original 
# format of the duration
yLabels <- function(x)
{
  x <- seconds_to_period(x)
  paste(hour(x),minute(x),second(x), sep = ':')
}

ggplot(d, aes(x=column1, y=c3, fill=column2)) + 
  geom_bar(position=position_dodge(),stat="identity") + 
  scale_y_continuous(labels = yLabels)

【讨论】:

  • 感谢 r_alanb。它对我有用。我不知道润滑。我将探索更多的图书馆。
猜你喜欢
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 2018-08-15
  • 1970-01-01
相关资源
最近更新 更多