如何融合我的数据以创建条形图?

时间:2019-09-04 12:34:16

标签: r ggplot2 time

我想使用ggplot创建比较不同活动持续时间的条形图。在y轴上,我想以小时和分钟为单位,在x轴上使用活动标签。

我正在努力的是如何转换数据以及如何将其转换为时间格式。

此刻,时间以10分钟为间隔表示,例如。 460/60 = 7小时40分钟

我的数据格式如下:

structure(list(Sleep = c(460, 420, 500, 600, 280, 700, 420, 500, 
600, 460), `Tv and video` = c(200, 60, 140, 120, 0, 300, 80, 
210, 140, 340), `Main job` = c(0, 0, 500, 0, 420, 0, 0, 0, 0, 
0), `Social life` = c(210, 260, 60, 20, 40, 0, 410, 180, 160, 
70), Eating = c(90, 80, 50, 120, 90, 60, 120, 90, 60, 120), `Travel by purpose` = c(180, 
140, 0, 60, 190, 10, 70, 70, 100, 140), `Other personal care` = c(60, 
70, 40, 30, 90, 60, 130, 60, 0, 140), `Food management` = c(110, 
190, 10, 90, 0, 40, 0, 70, 90, 20), `Radio and music` = c(0, 
0, 0, 110, 0, 0, 0, 0, 60, 0), `Childcare of own household member` = c(30, 
50, 80, 0, 0, 20, 0, 0, 140, 0)), row.names = c(NA, 10L), class = "data.frame")

非常感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以首先使用两列“类”和“值”将数据列收集为长格式。然后,您可以按类对值求和。最后,您可以创建一个小条图,直接在其中使用值(stat =“ identity”)。主题在x轴上旋转了标签的轴。

# Libraries
library(tidyr)
library(dplyr)
library(ggplot2)

# Gathering, summarizing and plotting data
data %>% 
  gather("class", "value", 1:10) %>%
  group_by(class) %>%
  summarise(total = sum(value)) %>%
  ggplot(., aes(class, total)) + geom_bar(stat = "identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

答案 1 :(得分:0)

您可以尝试

library(tidyverse)                                                                                                                                                                                                                                                                                                                                                                                                                                                           
df %>% 
  gather(k, v) %>% 
  mutate(v=v/60) %>% 
  mutate(k = gsub(" ", "\n", k)) %>% 
  ggplot(aes(reorder(k,-v), v)) + 
   geom_col() +
   ylab("Hours") + xlab("Activities")

enter image description here

可以使用此添加文字

df %>% 
  gather(k, v) %>% 
  mutate(k = gsub(" ", "\n", k)) %>% 
  group_by(k) %>% 
  summarise(v=sum(v)/60) %>% 
  ggplot(aes(reorder(k,-v), v, label = round(v,1))) + 
  geom_col() +
  geom_text(nudge_y = 2) +
  ylab("Hours") + xlab("Activities")