ggplot2:如何修复分类变量的“压扁”y轴?

时间:2017-07-14 20:43:43

标签: r ggplot2 data.table axes

我正在尝试在此条形图中增加y轴上标签的间距:

library(data.table)    
ggplot(data, aes(y=values, x=categories)) + 
             geom_bar(stats="identity") +coord_flip()

enter image description here

问题当然是有大约1500个y轴分类标签。目前,这些被压扁在一起,无法看到数据的任何趋势。

如何增加这些y轴标签之间的间距?我可以将地块垂直放大吗?

当然,人们可以减少文字大小或减少条形的宽度,但这仅适用于某一点......

我使用?discrete_scale尝试了以下解决方案:

ggplot(data, aes(y=values, x=categories))
           +geom_bar(stats="identity") +coord_flip() + scale_x_discrete(expand = c(0,0.01))

然而,摆弄expand似乎并没有在这些标签之间创造空间。

1 个答案:

答案 0 :(得分:3)

There isn't really a trick answer here. If you have an 8 inch tall image, and 1500 rows of text, the text is either going to be heavily overlapped or tiny. Either way it will not be readable. One option is to just turn off the y labels. theme(axis.ticks.y = element_blank(), axis.text.y = element_blank()). Note you may need to change those to axis.ticks.x and axis.text.x depending on the coord_flip. Another option is to sample your dataset. Instead of plotting everything, just plot a randomly selected 100 rows. ggplot(data[sample(dim(data)[1], 100)], aes(....

If you really want every label, and every row of data, the third option is to just make a very tall image.

pdf(file = "image.pdf", width = 8, height = 120)
g <- ggplot(data, aes(y = values, x = categories)) + 
  geom_bar(stats="identity") + 
  coord_flip()
print(g)
dev.off()