Reputation: 1098
I can't seem to get geom_label to label a dodged bar plot by CLASS
(the factor by which the plot is "dodged"). Rather, I am getting the total count
per PROC
(the Y
axis):
ggplot(data = df, mapping = aes(x = PROC)) +
geom_bar(mapping = aes(fill = CLASS), position = "dodge") +
geom_text(stat = "count", aes(x = PROC, label = ..count..)) +
theme(axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.ticks.y = element_blank(),
axis.ticks.x = element_blank(),
axis.text.x = element_blank()) +
scale_x_discrete(labels = function(x) str_wrap(
PROC.Labels,
width = 10)) +
coord_flip()
Additionally, I don't know why the 105 geom_text
label is appearing so far to the right of this bar plot.
Upvotes: 2
Views: 1497
Reputation: 11957
You need to update geom_text
to use the position_dodge()
function. Here's an example, very similar to yours, using the built-in diamonds data set. I'm also using ggplot 3.0's stat()
function, rather than the deprecated ..count..
variable.
Your labels appear far to the right because they represent the total count for each of your groups, and are thus placed at the corresponding higher (farther right) y position.
Note that providing position_dodge()
a width value of 0.9 corresponds to the fact that by default, a categorical bar (or a dodged group of bars) takes up 90% of its available space on the axis, with the remaining 10% going to the margin between the bar groupings.
g <- ggplot(data = diamonds, aes(x = cut, fill = color)) +
geom_bar(position = 'dodge') +
geom_text(stat = 'count', hjust = 0, position = position_dodge(0.9), aes(x = cut, label = stat(count))) +
coord_flip()
print(g)
Upvotes: 6