在条形图上跳过重叠的x轴标签

时间:2018-09-20 08:45:19

标签: r ggplot2

我有一个相当大的年份数据集,分为两个因素,并且我想生成一个堆积的条形图,显示每年两个因素之间的比率。我使用了以下ggplot2代码:

library(ggplot2)
ggplot(data=table, aes(x=years, y=Freq, fill=label)) + 
  geom_bar( stat="identity")+
  labs(x="Hire Year", y="Number of Employees")

这是哪个情节

enter image description here

由于柱形的数量很多,每个柱形的年份标签重叠,所以我需要一种方法来仅显示例如第4年的第3年,因为它们无论如何都是连续的。

2 个答案:

答案 0 :(得分:1)

在x轴上使用主要/次要中断+标签

df <- data.frame( x = seq(0,100,1),
                  y = seq(0,100,1) )

ggplot(df, aes( x = x, y = y) ) + 
  geom_line() +
  scale_x_continuous( breaks = seq(0,100,5), 
                      labels = seq(0, 100, 5), 
                      minor_breaks = seq(0,100,1) )

enter image description here

答案 1 :(得分:0)

您可以旋转轴标签来代替移除。例如...没有旋转的x轴标签...

library(ggplot2)
library(lubridate)
ggplot(data=economics, aes(x=year(date), y=unemploy)) + 
  geom_bar( stat="identity")

plot with horizontal x-axis labels

通过将theme(axis.text.x = element_text(angle = 90, hjust =1, vjust = 0.5))添加到绘图中,可以旋转x轴标签。

ggplot(data=economics, aes(x=year(date), y=unemploy)) + 
  geom_bar( stat="identity") +
  theme(axis.text.x = element_text(angle = 90, hjust =1, vjust = 0.5))

请注意,vjust控制垂直调整。 0.5表示我们希望这些标签居中。

plot with rotated x-axis labels