添加标签到likert scale ggplot graph

时间:2016-05-04 22:51:45

标签: r ggplot2

我想在手工制作的情节中添加标签。但是,当我尝试添加标签时,我只在右侧/位置获得一些值,如图所示。为什么它不起作用?

的软件包:

   library(dplyr)
    library(tidyr)
    library(ggplot2)
    library(scales)

数据示例:

Servicos <- read.table(text="Serviços, Muito, Pouco, Nunca, NS/NR
A,.513,.328,.081, .078
B,.387,.423,.109,.081
C, .301, .384, .209, .105
D, .355, .344, .204, .097
E,  .317, .412, .191, .080
F, .092, .474, .341, .093", sep=",", header=TRUE, stringsAsFactors=FALSE)


  Servicos %>%
        gather(Response, percent, -Serviços) -> likert


    likert %>%
        filter(Response=="NS.NR") %>%
        arrange(desc(percent)) %>% .$Serviços -> ind_order


    likert %>%
        mutate(Serviços=factor(Serviços, levels=ind_order, ordered=TRUE)) %>%
        mutate(Response=factor(Response,
                               levels=c("Muito", "Pouco", "Nunca", "NS.NR"), ordered=TRUE,
                               labels=c("Muito", "Pouco", "Nunca", "NS/NR"))) %>%
        mutate(percent=ifelse(Response %nin% c("Muito", "Pouco", "NS/NR"), -percent, percent)) -> lik

情节:

gg <- ggplot()
gg <- gg + geom_hline(yintercept=0)
gg <- gg + geom_bar(data=filter(lik, percent<0), width=.75,
                    stat="identity", position="stack",
                    aes(x=Serviços, y=percent, fill=Response))
gg <- gg + geom_bar(data=filter(lik, percent>=0), width=.75,
                    stat="identity", position="stack",
                    aes(x=Serviços, y=percent, fill=Response))
gg <- gg + geom_text(data=filter(lik, percent<0), aes(x=Serviços, y=percent, group=Response,label = percent))
gg <- gg + scale_x_discrete(expand=c(0, .75))
gg <- gg + scale_fill_manual(values=c( "#4393c3", "#92c5de","#b2182b", "gray"),
                             drop=FALSE)
gg <- gg + scale_y_continuous(expand=c(0,.10),
                              breaks=seq(-.35, 1, .25),
                              limits=c(-.35, .95),
                              labels=percent_format())
gg <- gg + coord_flip()
gg <- gg + theme_bw()
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(panel.border=element_blank())
gg <- gg + theme(panel.grid.major.y = element_blank()) 
gg <- gg + theme(panel.grid=element_blank())
gg

enter image description here

2 个答案:

答案 0 :(得分:1)

根据mpalanco的部分答案,您可以使用geom_text的两个不同行解决此问题:

gg <- gg + geom_text(data=filter(lik, percent<0), aes(x=Serviços, y = percent, group=Response,label = paste(percent*100, "%")), position = "stack", hjust = -.2, size = 2.5, color="white")

gg <- gg + geom_text(data=filter(lik, percent>0), aes(x=Serviços, y = percent, group=Response,label = paste(percent*100, "%")), position = "stack", hjust = 1, size = 2.5)

enter image description here

答案 1 :(得分:0)

要显示百分比值,请在行中添加label = paste(percent*100, "%")

gg <- gg + geom_text(data=filter(lik, percent<0), aes(x=Serviços, y=percent, group=Response,label = paste(percent*100, "%")))

enter image description here