具有唯一子组名称的组的条形图

时间:2018-07-02 16:33:38

标签: r ggplot2

这与this question非常相似,但希望有足够的区别,值得提出一个新问题。

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

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

有点像

plot

示例数据:

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")

2 个答案:

答案 0 :(得分:0)

这对我有用:

# Create a new label which is concatenation of group and id
allBinsTop5.m$newlabel<-paste0("G",allBinsTop5.m$grp_id ,"-ID",allBinsTop5.m$short_text)

# Add a geom_text command that specifies new label along with dodge 
ggplot(allBinsTop5.m, aes(grp_id, value)) +   
    geom_bar(aes(fill = newlabel), position = "dodge", stat="identity") + 
    geom_text(aes(label=newlabel),position=position_dodge(width=.9),
              vjust=allBinsTop5.m$value)+
    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")

答案 1 :(得分:0)

可以使用this answer中提供的代码来解决我的问题。

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")

plot with multiple groups and unique sub-groups labels