[R] ggplot2 geom_bar label justification
Brian Smith
bsmith030465 at gmail.com
Wed Jun 28 00:03:38 CEST 2017
Hi,
I was trying to make a horizontal bar plot. The barplot works when the text
labels are of reasonable length, but not if some of them are slightly long.
I think the long ones get 'squeezed' by default before the plot is flipped
and keep the skew after the flip. Is there a way I can get around this?
In the code below, plot px looks just fine, but the labels get staggered in
plot py.
#########
Lab1 = c("Tom","Harry","Brad","Helen","Julie","Steve")
Lab2=c('abracadabra','rumplestiltskin','adadf','asddsdfsdsfsds','sdfsdfsfsfs','sddf')
valuex = c(3.1,2.3,0.4,-0.4,-1.2,-4.4)
df1 <- data.frame(Lab1,Lab2,valuex)
df1$hjust <- ifelse(df1$valuex > 0, 1.3, -0.3)
df1$Lab1 <- factor(df1$Lab1, levels = unique(df1$Lab1))
df1$Lab2 <- factor(df1$Lab2, levels = unique(df1$Lab2))
## plot 1
px <- ggplot(df1,aes(Lab,valuex,label=Lab1,hjust = hjust)) +
geom_text(aes(y=0,size=5)) +
geom_bar(stat = "identity")
px <- px + coord_flip()
## plot 2
py <- ggplot(df1,aes(Lab,valuex,label=Lab2,hjust = hjust)) +
geom_text(aes(y=0,size=5)) +
geom_bar(stat = "identity")
py <- py + coord_flip()
#########
many thanks for your help!
[[alternative HTML version deleted]]
More information about the R-help
mailing list