堆积条*为图形带来标签*

时间:2016-02-14 12:42:21

标签: r ggplot2

我正在绘制堆积条形图并使用geom_text插入每个堆栈的值和名称。问题是一些堆栈非常小/很窄,因此两个堆栈的文本相互重叠,因此不是很可读。如何修改代码以解决此问题。

 Type<-c("ddddddddddd","ddddddddddd","bbbbbbbbbbbbb","ddddddddddd","eeeeeeeeeeeeee","bbbbbbbbbbbbb","ddddddddddd","bbbbbbbbbbbbb","ddddddddddd",
        "eeeeeeeeeeeeee","mmmmmmmmmmmmmmmmmmm","bbbbbbbbbbbbb","ddddddddddd","bbbbbbbbbbbbb","eeeeeeeeeeeeee")
        Category<-c("mmmmm","mmmmm","gggggggggggggggggg","ffffffffffff","ffffffffffff","ffffffffffff","sanddddddddd","sanddddddddd","yyyyyyyyyyy",
        "yyyyyyyyyyy","yyyyyyyyyyy","sssssssssssssss","sssssssssssssss","sssssssssssssss","ttttttttttttt")
        Frequency<-c(4,1,30,7,127,11,1,1,6,9,1,200,3,4,5)
        Data <- data.frame(Type, Category, Frequency)   
        p <- ggplot(Data, aes(x = Type, y = Frequency)) +
          geom_bar(aes(fill = Category), stat="identity", show.legend = FALSE) +
          geom_text(aes(label = Frequency), size = 3) +
          geom_text(aes(label = Category), size = 3)

1 个答案:

答案 0 :(得分:1)

考虑到您的数据,分面图可能是更好的方法:

# summarise your data
library(dplyr)
d1 <- Data %>% 
  mutate_each(funs(substr(.,1,2)),Type,Category) %>%
  group_by(Type,Category) %>% 
  summarise(Freq = sum(Frequency)) %>%
  mutate(lbl = paste(Category,Freq)) # create a label by pasting the 'Category' and the 'Freq' variables together

# plot
ggplot(d1, aes(x = Category, y = Freq, fill = Category)) +
  geom_bar(stat="identity", width = 0.7, position = position_dodge(0.8)) +
  geom_text(aes(label = lbl), angle = 90, size = 5, hjust = -0.1, position = position_dodge(0.8)) +
  scale_y_continuous(limits = c(0,240)) +
  guides(fill = FALSE) +
  facet_grid(.~Type, scales = "free", space = "free") +
  theme_bw(base_size = 14)

给出:

enter image description here

在上图中,我故意缩短了标签。如果你不想这样做,你可以考虑这个:

d2 <- Data %>%
  group_by(Type,Category) %>% 
  summarise(Freq = sum(Frequency)) %>%
  mutate(lbl = paste(Category,Freq))

ggplot(d2, aes(x = Category, y = Freq, fill = Category)) +
  geom_bar(stat="identity", width = 0.7, position = position_dodge(0.8)) +
  geom_text(aes(y = 5, label = lbl), alpha = 0.6, angle = 90, size = 5, hjust = 0, position = position_dodge(0.8)) +
  scale_y_continuous(limits = c(0,240)) +
  guides(fill = FALSE) +
  facet_grid(.~Type, scales = "free", space = "free") +
  theme_bw(base_size = 14) +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

给出:

enter image description here