R- 4组,3个子组中的分组条形图

时间:2018-10-03 01:33:52

标签: r graph

我正在尝试在R中绘制这些数据

group1(extremely obese=1.3, obese=8.6, overweight=10.9)

group2(extremely obese=8.6, obese=19.5, overweight=15.7)

group3(extremely obese  =7.6, obese =21.9, overweight 1=7)

group4(extremely obese=4.4, obese=14.7, overweight=13.8)

我尝试了教程中建议的许多代码,但是我一直遇到红色脚本问题。 经常说“数据框错误”,条形图公式错误,找不到主题。

我希望数据在分组的条形图中,其中x轴具有1-4组,其子组为(极度肥胖,肥胖,超重),而y轴为代表百分比的相应数字。 / p>

如何显示此内容?

1 个答案:

答案 0 :(得分:0)

尽管我同意Jon Spring的观点,这个问题过于笼统,但我还是面临挑战,要以给定的格式获取数据并创建所需的图表。

任务需要读入数据,从宽到长格式整形并创建绘图:

# dataset as posted by the OP
txt <- "
group1(extremely obese=1.3, obese=8.6, overweight=10.9)

group2(extremely obese=8.6, obese=19.5, overweight=15.7)

group3(extremely obese  =7.6, obese =21.9, overweight =17)

group4(extremely obese=4.4, obese=14.7, overweight=13.8)
"

library(data.table)
library(magrittr)
library(ggplot2)

txt %>% 
  # turn special characters into column separators
  gsub("[(=)]", ",", .) %>% 
  # read 
  fread(., blank.lines.skip = TRUE) %>%
  # reshape from wide to long format with two value columns
  .[, melt(.SD, "V1", list(c("V2", "V4", "V6"), c("V3", "V5", "V7")),
           value.name = c("subgroup", "percent"))] %>% 
  # rename first column
  .[, setnames(.SD, "V1", "group")] %>% 
  # create chart
  ggplot() +
  aes(group, percent, fill = subgroup) +
  geom_col(position = "dodge")

enter image description here