我在ggplot2中使用facet_grid创建了一对条形图。我已根据自己的喜好自定义了所有内容,除了带标签。我想出了如何使用strip.text.y = element_blank()关闭条形标签,然后将标签移动到图表的左侧(开关)。但是,都不令人满意。我想将标签放在顶部或制作一个图例。如果我可以将它们移到每个图的顶部,则可能要删除条形背景并调整文本的位置,对每个图的右侧说。我找到了对strip.position元素的引用,但是它对我不起作用。
我尝试了strip.position,但是无法正常工作。实际上,在R Studio中键入代码时,strip.position并没有显示为选项。
cage<-c(3:11)
sage<-c(2:8,10,12:16)
Age<-c(cage,sage)
c<-rep("Choptank",9)
s<-rep("Severn",13)
River<-c(c,s)
n<-c(2,35,19,4,1,52,4,3,2,1,2,39,11,5,2,57,2,1,3,4,2,2)
B<-data.frame(River,Age,n) %>%
group_by(River,Age) %>%
tally() %>%
mutate(prop=n/sum(n))
bartheme<- theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.spacing.y=unit(1, "lines"),
axis.line = element_line(size = 1,colour = "black"),
axis.title = element_text(colour="black",
size = rel(1.5)),
plot.title = element_text(hjust = 0.5, size=14),
plot.subtitle = element_text(hjust = 0.5,size=14),
panel.background = element_rect(fill="whitesmoke"),
axis.text = element_text(colour = "black",
size = rel(1)))
Bplot <- ggplot(data = B,
aes(x = Age, y =prop))+
geom_bar(stat = 'identity', position =
position_dodge(),fill="dodgerblue")+
geom_text(aes(label=round(prop,2)), vjust=-0.3, size=3.5)+
facet_grid(rows=vars(River))+
scale_y_continuous(limits=c(0,1), oob=rescale_none,expand=c(0,0))+
scale_x_continuous(breaks=c(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16))
Bplot+bartheme+ggtitle("Age distribution of white
perch")+ylab("Proportion")
我按预期获得了堆叠的地块,每个地块的右侧都带有条形标签(垂直文本)。我希望将条形标签放置在每个图的顶部-最好对外观进行一些控制。
答案 0 :(得分:0)
使用facet_wrap
可以更好地控制构面的布局,并且可以使用strip
前缀的主题元素来控制构面标签的外观。有关详细信息,请参见here。
以下是您的数据的一个示例,该示例将标签放置在图形上方并删除阴影,并右对齐文本。我不确定这是否正是您要寻找的东西,但它应该为您提供根据您的喜好进行调整的工具。
bartheme <- theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.spacing.y=unit(1, "lines"),
axis.line = element_line(size = 1,colour = "black"),
axis.title = element_text(colour="black", size = rel(1.5)),
plot.title = element_text(hjust = 0.5, size=14),
plot.subtitle = element_text(hjust = 0.5,size=14),
panel.background = element_rect(fill="whitesmoke"),
axis.text = element_text(colour = "black", size = rel(1)),
strip.background = element_blank(),
strip.text = element_text(hjust = 1)
)
Bplot <-
ggplot(data = B, aes(x = Age, y = prop)) +
geom_bar(stat = 'identity', position = position_dodge(), fill = "dodgerblue") +
geom_text(aes(label = round(prop, 2)), vjust = -0.3, size = 3.5) +
facet_wrap(vars(River), ncol = 1) +
scale_y_continuous(limits=c(0,1), oob=rescale_none,expand=c(0,0))+
scale_x_continuous(breaks = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
Bplot + bartheme + ggtitle("Age distribution of white perch") + ylab("Proportion")