r - ggplot2 bar plot: hjust depending on bar and label size -
being new r, produced simple horizontal bar plots using ggplot2 , coord_flip()
. notably, insert values of x variable @ left side of bar default (or @ right side if label not fit) using following command:
geom_text(aes(x=type, y=count, ymax=count, label=count, hjust=ifelse(count>1000, 1.5, -0.3)), size=3.5, position = position_dodge(width=0.8))
the problem that, depending on data-sets, x values can vary (e.g. dataset_1 x values can between 1 200; dataset_2 x values can between 10,000 100,000; ...), causes label of shortest bar misplaced ifelse
statement using (see brown bar in figure below). in case cannot use constant count>1000
condition datasets.
figure a:
i modify manually value of hjust=ifelse(count>1000,...
statement each dataset. wondering if possible automatically move label outs of bar if not fit between axis , top of bar without modifying value of ifelse
condition each dataset, in figure b below.
figure b :
editworkaround (not perfect better): placing label @ right of bar if value less 5% of maximum value
maxi <- max(data[,2]) geom_text(aes(x=type, y=count, ymax=count, label=count, hjust=ifelse((count/maxi)<0.05, -0.3, 1.3)))
having labels outside bars , inside can distort visual encoding of magnitude length of bar. option put values in middle of bar set geom_text
skip values small relative maximum bar. or, if want include text bar values added, can put them below bars in order keep clean visual pattern bar lengths. examples of both options below:
# fake data dat = data.frame(x = letters[1:5], y=c(432, 1349, 10819, 5489, 12123)) ggplot(dat, aes(x, y, fill=x)) + geom_bar(stat="identity") + geom_text(aes(label=ifelse(y < 0.05*max(dat$y), "", format(y, big.mark=",")), y=0.5*y), colour="white") + coord_flip(xlim=c(0.4,5.6), ylim=c(0, 1.03*max(dat$y)), expand=false) + guides(fill=false) ggplot(dat, aes(x, y, fill=x)) + geom_hline(yintercept=0, lwd=0.3, colour="grey40") + geom_bar(stat="identity") + geom_text(aes(label=format(y, big.mark=","), y=-0.01*max(dat$y)), size=3.5, hjust=1) + coord_flip(ylim = c(-0.04*max(dat$y), max(dat$y))) + guides(fill=false)
Comments
Post a Comment