首页 > 解决方案 > 具有唯一子组名称的组的条形图

问题描述

这与这个问题非常相似,但希望足够不同,值得提出一个新问题。

我在 R 中的年度时间序列数据中对我的值(“小时”)最多有 5 个观察值。因此,每个观察值都包含一个年份组(grp_id)和它自己的唯一 ID(short_text)。

我想在 ggplot2 的单个条形图中显示所有观察值(小时),每年,在 ggplot2 的单个条形图中(根据唯一 ID,short_text 设置为闪避),但希望每个观察的唯一 ID(short_text)运行沿 x 轴,除了年度组名称 (grp_id)。

有点像这样

阴谋

示例数据:

structure(list(short_text = 1:20, grp_id = c(3, 3, 4, 4, 4, 4, 
4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7), variable = c("hours", 
"hours", "hours", "hours", "hours", "hours", "hours", "hours", 
"hours", "hours", "hours", "hours", "hours", "hours", "hours", 
"hours", "hours", "hours", "hours", "hours"), value = c("1371.28228277413", 
"4117.61650085692", "4462.05401592845", "4563.63839159463", "6617.47698685436", 
"10498.3641321107", "20735.9579131878", "14838.8668295674", "14884.5002478823", 
"15846.5620639966", "20996.7282642214", "73321.8056031507", "29960.4636692291", 
"32475.8922108366", "35534.418796457", "49040.3036856129", "121255.358807715", 
"15288.7191802188", "69888.6583792545", "127734.59190842")), .Names = c("short_text", 
"grp_id", "variable", "value"), row.names = c(NA, 20L), class = "data.frame")

到目前为止,我最接近的是这个,但唯一的 ID 不会沿着 x 轴显示:

ggplot(allBinsTop5.m, aes(grp_id, value)) +   
  geom_bar(aes(fill = short_text), position = "dodge", stat="identity") + 
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1),
        legend.position="none")

标签: rggplot2

解决方案


可以使用此答案中提供的代码来解决我的问题。

ggplot(data = aa, aes(x = short_text, y = value, fill = short_text)) + 
  geom_bar(stat = "identity", width = 1) +
  facet_wrap(~grp_id, strip.position = "bottom", scales = "free_x") +
  theme(panel.spacing = unit(0, "lines"), 
        strip.background = element_blank(),
        strip.placement = "outside") + 
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust=1),
        legend.position="none")

具有多个组和唯一子组标签的绘图


推荐阅读