【问题标题】:Add number in a barplot ggplot2 [duplicate]在条形图ggplot2中添加数字[重复]
【发布时间】:2019-01-17 00:06:40
【问题描述】:

将百分比添加到条形图时(请参见下面的代码),属于同一“变量”的三个百分比处于相同高度,因此未与各自的条对齐。怎么改?

#Sum plot
myd<- data.frame( var1 = rep(c("Newly infected","Mortality","TDR level"),each=3), 
                     samp = rep(c("Scen1","Scen2","Scen3"),3), 
                  V3 = c(3.5,2,NA,8,2,NA,4,5,NA)/1.5, V2 = c(3.5,2,NA,8,3,NA,4,4.3,NA), V1 = c(1.5,0.2,5,5,3,0.2,4,-5,2) ) 

# rshaping data to long form for ggplot2 
library(reshape2)
library(ggplot2)
meltd<- melt(myd, id.vars=1:2) 

ggplot(meltd, aes(x=var1, y=value, fill=variable)) +
  geom_bar(stat="identity",position=position_dodge(width=0.6),width=0.5) +
  facet_grid(samp~., switch = "y", scales = "free_y", space = "free") +
  theme_bw()+
  theme(legend.position = "bottom")+
  theme(strip.placement = "outside")+
  theme(axis.title.x = element_blank()) +
  theme(axis.title.y = element_blank()) +
  theme(axis.text.y = element_text(colour="black"))+
  theme(strip.text.y = element_text(size = 12, colour = "black"))+
  #scale_y_continuous(labels=percent,limits = c(0,1))
  coord_flip()+
  scale_fill_manual("legend", values = c("V3"="orange","V2" = "red", "V1" = "blue", "Baseline" = "black"))+
  geom_text(data=meltd, aes(label=paste0(round(value*100,1),"%"), y=value+0.4*sign(value)), size=4)

【问题讨论】:

标签: r ggplot2


【解决方案1】:

你是这个意思吗?

ggplot(meltd, aes(x = var1, y = value, fill = variable, label = paste0(round(value * 100, 1), "%"))) +
    geom_bar(stat = "identity", position = position_dodge(width = 0.6), width = 0.5) +
    facet_grid(samp ~ ., switch = "y", scales = "free_y", space = "free") +
    coord_flip() +
    scale_fill_manual(
        "legend",
        values = c("V3" = "orange", "V2" = "red", "V1" = "blue", "Baseline" = "black")) +
    geom_text(aes(y = value + 0.4 * sign(value)), position = position_dodge(width = 0.6)) +
    theme_bw() +
    theme(
        legend.position = "bottom",
        strip.placement = "outside",
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y = element_text(colour="black"),
        strip.text.y = element_text(size = 12, colour = "black"))

geom_text 中使用position = position_dodge(width = 0.6) 来躲避标签(相当于躲避geom_bar 中的条形)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多