ggplot标签在分组条形图中的定位

时间:2016-02-23 16:02:58

标签: r ggplot2

我刚刚使用ggplot一段时间后才进入spplot并且到目前为止真的很喜欢它。但是,我现在陷入了一个小问题。

我有一个分组的条形图,并希望将值标签放在每个条形图的顶部。但它不是以单个条形为中心,而是以每个组的中间为中心。试图摆弄vjust / hjust,但我认为问题出在其他地方。任何提示?

这里有一些可以重现的东西:

loocvRSQR_OK <- c(0.7611536,0.6945638,0.6886343,0.8015664,0.7593292)
loocvRSQR_IDW <- c(0.7328284,0.6480901,0.5107468,0.7894640,0.7495850)
kfoldRSQR_OK <- c(0.6403418,0.7132792,0.6318929,0.8363614,0.7875515)
kfoldRSQR_IDW <- c(0.5576863,0.5956204,0.4998972,0.8427054,0.7905995)
timestamp <- c("23.06.2009 23:00:00","24.06.2009 00:00:00","24.06.2009 01:00:00","24.06.2009 02:00:00","24.06.2009 03:00:00")
df <- data.frame(loocvRSQR_OK,loocvRSQR_IDW,kfoldRSQR_OK,kfoldRSQR_IDW,timestamp)

library(reshape)
dfm <- melt(df[,c('timestamp','loocvRSQR_OK','loocvRSQR_IDW', "kfoldRSQR_OK", "kfoldRSQR_IDW")],id.vars = 1)
dfm

valplot <- ggplot(dfm,aes(x = timestamp,y = value)) + 
  coord_cartesian(ylim = c(0.0, 1.00)) +
  geom_bar(aes(fill = variable),position = "dodge", stat="identity", width=0.9) +
  scale_fill_manual(values = c('#006D92', '#2EAAD4', '#9C30E4', '#B87AE1'), name="Foo bar") + xlab('Time') + ylab('Level of force') +
  geom_text(aes(label=round(value,digits=2)), vjust=0.5, position = position_dodge(0.9), color='black', size=3) +
  ggtitle("May the 4th be with you") + theme(plot.title = element_text(lineheight=.8, face="bold"))

valplot

1 个答案:

答案 0 :(得分:4)

您离我很近,将fill = variable移至ggplot的来电并稍加调整至vjust - vjust = -0.25

valplot <- ggplot(dfm, aes(x = timestamp, y = value, fill = variable)) + 
  coord_cartesian(ylim = c(0, 1)) + 
  geom_bar(position = "dodge", stat = "identity", width = 0.9) + 
  scale_fill_manual(
    values = c("#006D92", "#2EAAD4", "#9C30E4", "#B87AE1"), 
    name = "Foo bar"
  ) +
  labs(
    title = "May the 4th be with you",
    x = "Time",
    y = "Level of force"
  ) + 
  geom_text(
    aes(label = round(value, digits = 2)), 
    position = position_dodge(width = 0.9), 
    vjust = -0.25, color = "black", size = 3
  ) +
  theme(
    plot.title = element_text(lineheight = 0.8, face = "bold")
  ) 
相关问题