Reputation: 391
I'm struggling with my code to create a barplot with ggplot2 in which I try to add y
values on top of the bars, but without moving the labels of the x
axis.
geom_text
works great to add values on the bars, but then I cannot adjust the x
axis labels properly when rotated by 45˚ (i.e. the last letter of the label sticked to the axis).
My data
dput(graph)
structure(list(x = structure(1:9, .Label = c("AAAAAAAAAAAAA",
"BBBBBBBB", "CCCCCCCCCCCCCCCC", "DDDDD", "EEEEEEEE", "FFFFFFF",
"GGGGGGGGGGGGGGG", "HHHHHHHHHHHHHH", "IIIII"), class = "factor"),
y = c(1L, 5L, 10L, 1000L, 20L, 15L, 45L, 30L, 35L)), .Names = c("x",
"y"), class = "data.frame", row.names = c(NA, -9L))
My code:
graph <- read.table("input.txt",header=T,sep=";")
output <- ggplot(graph,aes(x=x,y=y))+
geom_bar(stat="identity")+
geom_text(aes(label=y,y=(y+25)))+
scale_x_discrete()+
scale_y_continuous(limits=c(0,max(50 + graph$y)))+
theme(axis.text.x=element_text(angle=45,vjust=0))
print(output)
I cannot post an image of the output, but the plot looks fine except the tick marks of the x
axis fit to the middle of the x
labels instead of the last letter of the label.
Upvotes: 2
Views: 2456
Reputation: 121568
Here a ggplot2-like lattice version:
library(lattice)
library(latticeExtra)
barchart(y~x, data=dat,
scales = list(x = list(rot=45,cex=1.5)),
par.settings = ggplot2like(), axis = axis.grid,
panel=function(x,y,...){
panel.barchart(x,y,...)
panel.text(x,y,label=y,col='red',
adj=c(0.5,-0.5),cex=2)
})
EDIT
To decrease differences between bars levels , one idea here is to use log scale:
library(lattice)
library(latticeExtra)
barchart(y~x, data=dat,
scales = list(x = list(rot=45,cex=1.5),
y = list(log=10)),
par.settings = ggplot2like(), axis = axis.grid,
yscale.components = yscale.components.log10ticks,
panel=function(x,y,...){
panel.barchart(x,y,...)
panel.text(x,y,label=10^y,col='red',
adj=c(0.5,-0.5),cex=2)
})
Upvotes: 1
Reputation: 98429
You should add hjust=1
to axis.text.x=
and change vjust=0
to vjust=1
. To change appearance of bars you can try to use transformation of y values, for example, square root, with scale_y_sqrt()
. Only positions for geom_text()
should be adjusted.
output <- ggplot(graph,aes(x=x,y=y))+
geom_bar(stat="identity")+
geom_text(aes(label=y,y=(y+c(10,10,10,50,10,10,10,10,10))))+
scale_y_sqrt(limits=c(0,max(50 + graph$y)),breaks=c(10,100,250,500,1000))+
theme(axis.text.x=element_text(angle=45,vjust=1,hjust=1))
output
Upvotes: 4