ggplot2 中使用 n.breaks 的 x 轴标签问题 第一次尝试连续 x 轴第二次尝试给定 n.breaks 的连续 x 轴第三次尝试离散 x 轴,gear 作为因子

问题描述

我使用 n.breaks 为每个集群设置一个标签的 x 轴标记,这适用于 4、5、6 个集群。现在我用两个集群尝试了它,但它不再起作用了。 我像这样构建图表:

@H_502_3@country_plot <- ggplot(Data) + aes(x = Cluster) +
theme(legend.title = element_blank(),axis.title.y = element_blank()) +
geom_bar(aes(fill = country),stat = "count",position = "fill",width = 0.85) +
scale_fill_manual(values = color_map_3,drop = F) +
scale_x_continuous(n.breaks = max(unique(Data$Cluster))) + scale_y_continuous(labels = percent) +
ggtitle("Country")

并像这样导出:

@H_502_3@  ggsave("country_plot.png",plot = country_plot,device = "png",width = 16,height = 8,units = "cm")

当它工作时,它看起来像这样:

successful marks

但是对于两个集群,我得到了这样的结果,只有一个标记超出了实际的 2.5 条:

fail

我手动检查了

的返回值
@H_502_3@max(unique(Data$Cluster))

它返回 2,根据我的理解,这应该导致两个 x 轴标记为 1 和 2,就像它适用于更多集群一样。

编辑:

@H_502_3@mutate(country = factor(country,levels = 1:3)) %>% 
  mutate(country =fct_recode(country,!!!country_factor_naming))%>%
  mutate(Gender = factor(Gender,levels = 1:2)) %>% 
  mutate(Gender = fct_recode(Gender,!!!gender_factor_naming))%>%

解决方法

如果我理解正确,问题是由 Cluster 被视为连续变量引起的。它需要转化为一个因素。

这是一个使用 mtcars 数据集重现不需要的行为的最小的、可重现的示例:

第一次尝试(连续 x 轴)

library(ggplot2)
library(scales)
ggplot(mtcars) +
  aes(x = gear,fill = factor(vs)) +
  geom_bar(stat = "count",position = "fill",width = 0.85) +
  scale_y_continuous(labels = percent)

enter image description here

在本例中,gear 接管了 Cluster 的角色并被分配到 x 轴。

x = 2.5,3.5,4.5,5.5 处有不需要的标记刻度线,这是由于连续尺度。

第二次尝试(给定 n.breaks 的连续 x 轴)

ggplot(mtcars) +
  aes(x = gear,width = 0.85) +
  scale_x_continuous(n.breaks = length(unique(mtcars$gear))) +
  scale_y_continuous(labels = percent)

enter image description here

n.breaks 中指定 scale_x_continuous() 不会将 x 轴更改为离散。

第三次尝试(离散 x 轴,gear 作为因子)

gear变成一个因子时,我们为每个因子值得到一个标记的刻度线;

ggplot(mtcars) +
  aes(x = factor(gear),width = 0.85) +
  scale_y_continuous(labels = percent)

enter image description here