ggplot2将单条上的数字对齐 [英] Alignment of numbers on the individual bars with ggplot2

查看:471
本文介绍了ggplot2将单条上的数字对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下图中的单杠上显示数字。 (结构(c(1L,1L,1L,2L,2L,2L,1L,1L) 3L,3L,
3L),。标签= c(0-50,000,50,001-250,000,250,001-过),等级=因子),
B =结构c(1L,2L,3L,1L,2L,3L,1L,2L,3L),。标签= c(0-50,000,
50,001-250,000,250,001- =因子),Freq = c(0.507713884992987,
0.258064516129032,0.23422159887798,0.168539325842697,0.525280898876405,
0.306179775280899,0.160958904109589,0.243150684931507,
0.595890410958904)),.Names = c(A ,B,Freq),class =data.frame,row.names = c(NA,
-9L))

library(ggplot2)
p < - ggplot(data = df,aes(x = A,y = Freq))+
geom_bar(aes(fill = B),position = position_dodge())+ theme_bw()
p< - p + scale_y_continuous(formatter =percent)
p < - p + geom_text(aes(label = paste(sprintf(%。1f,Freq * 100),%,sep =) ,y = Freq + 0.015,x = A),size = 3)
print(p)



我无法弄清楚如何将数字放在x轴的正确位置。任何帮助将非常感激。谢谢

解决方案

您需要添加 position = position_dodge(width = 0.9)给geom_text调用。



清理一下你的代码会给出:

  p <-ggplot(data = df,aes(x = A,y = Freq))+ 
geom_bar(aes(fill = B),position = position_dodge())+
geom_text (aes(label = paste(sprintf(%。1f,Freq * 100),%,sep =),
y = Freq + 0.015,x = A),
size = 3,position = position_dodge(width = 0.9))+
scale_y_continuous(formatter =percent)+
theme_bw()

导致


I want to show numbers on the individuals bars in the following graph.

df <- structure(list(A = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), .Label = c("0-50,000", "50,001-250,000", "250,001-Over"), class = "factor"),
    B = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0-50,000",
    "50,001-250,000", "250,001-Over"), class = "factor"), Freq = c(0.507713884992987,
    0.258064516129032, 0.23422159887798, 0.168539325842697, 0.525280898876405,
    0.306179775280899, 0.160958904109589, 0.243150684931507,
    0.595890410958904)), .Names = c("A", "B", "Freq"), class = "data.frame", row.names = c(NA,
-9L))

library(ggplot2)
p <- ggplot(data=df, aes(x=A, y=Freq))+
            geom_bar(aes(fill=B), position=position_dodge()) + theme_bw()
p <- p + scale_y_continuous(formatter="percent")
p <- p + geom_text(aes(label = paste(sprintf("%.1f", Freq*100), "%", sep=""), y = Freq+0.015, x=A), size = 3)
print(p)

I could not figure out how to put the numbers in the right position along x-axis. Any help will be highly appreciates. Thanks

解决方案

You need to add position=position_dodge(width=0.9) to the geom_text call.

Cleaning up your code a little gives:

p <- ggplot(data=df, aes(x=A, y=Freq))+
    geom_bar(aes(fill=B), position = position_dodge()) + 
    geom_text(aes(label = paste(sprintf("%.1f", Freq*100), "%", sep=""),
                  y = Freq+0.015, x=A),
              size = 3, position = position_dodge(width=0.9)) +
    scale_y_continuous(formatter = "percent") +
    theme_bw()

which results in

这篇关于ggplot2将单条上的数字对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆