ggplot2 geom_bar轴限制... x轴限制和标签

时间:2015-10-21 13:59:43

标签: r ggplot2

我已经浏览了很多,但不幸的是我只是发现了模糊的信息。我希望显示长度等级的性别比例。为了达到这个目的,我用ggplot2(geom_bar)做了一个叠加的条形图。这是代码:

kcores(net)

cols只是一个带有颜色的简单矢量。

这是到目前为止的情节:

enter image description here

我的问题是我无法更改轴文本。我只想要每隔五个条形下面的文字,否则它们是重叠的。我尝试使用limits和breaks命令,但这只是给了我一个空图。

Data <- data.frame(LCnew=c(30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40), 
                   sex=c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2))
ggplot(Data, aes(x=factor(LCnew), fill=factor(sex)))+geom_bar(position="fill") +  scale_x_discrete("Lengthclass [mm]") +  scale_y_continuous("Proportion of sexes") + scale_fill_manual(values=cols)

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

如果您想防止标签重叠,可以遵循以下几种策略:

1)定义休息时间:

ggplot(y, aes(x=factor(length), fill=factor(sex))) +
  geom_bar(position="fill", width=0.7) +
  scale_x_discrete("Standard Length [mm]", breaks=c(300000,350000,400000)) +
  scale_y_continuous("Proportion of sexes", expand=c(0,0)) + 
  scale_fill_manual("Sex", values=c("blue","pink"), labels=c("Male","Female")) +
  theme_minimal()

给出了以下情节:

enter image description here

2)更改标签的角度:

ggplot(y, aes(x=factor(length), fill=factor(sex))) +
  geom_bar(position="fill", width=0.7) +
  scale_x_discrete("Lengthclass [mm]", expand=c(0,0)) +
  scale_y_continuous("Proportion of sexes", expand=c(0,0)) + 
  scale_fill_manual("Sex", values=c("blue","pink"), labels=c("Male","Female")) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle=90, vjust = 0.5))

给出:

enter image description here

3)旋转情节:

ggplot(y, aes(x=factor(length), fill=factor(sex))) +
  geom_bar(position="fill", width=0.7) +
  scale_x_discrete("Lengthclass [mm]", expand=c(0,0)) +
  scale_y_continuous("Proportion of sexes", expand=c(0,0)) + 
  scale_fill_manual("Sex", values=c("blue","pink"), labels=c("Male","Female")) +
  coord_flip() +
  theme_minimal()

给出:

enter image description here

使用过的数据

y <- structure(list(length = c(300000, 300000, 310000, 310000, 320000, 320000, 330000, 330000, 340000, 340000, 350000, 350000, 360000, 360000, 370000, 370000, 380000, 380000, 390000, 390000, 400000, 400000, 300000, 310000, 330000, 340000, 360000, 380000, 390000), 
                    sex = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2)), .Names = c("length", "sex"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "110", "41", "71", "101", "131", "171", "201"), class = "data.frame")

答案 1 :(得分:1)

尝试添加&#39;标签&#39;

scale_x_continuous("Standard Length [mm]", breaks=c(30,35,40,45,50,55,60,65,70,75,80,85),labels=c(30,35,40,45,50,55,60,65,70,75,80,85))