Liztc
Liztc

Reputation: 5

How to add labels into the bars in a bar graph using ggplot2 in R?

I can't put the label inside the bin, only on the top :(. How could I put them inside the bins? Also, I would like to have a white chart, but the chart behind the bins are grey, how could I change it for white?

ggplot(region,
       aes(x=reorder(Field_Partner_Name,-amount), y=amount, fill=Field_Partner_Name)) +
  geom_bar(stat="identity")+
  ggtitle("Partners that invest more money") +
  labs(x="Partners",y="Amount")+
  geom_text(aes(label = Field_Partner_Name, hjust=0),
            position = position_dodge(width = 0.9), angle = 90) +
  scale_y_continuous(expand = c(0.15, 0))+
  theme(axis.text.x=element_blank(),
        legend.position = "none") +
  ylim(0,90000000)

Upvotes: 0

Views: 773

Answers (1)

user11538509
user11538509

Reputation:

Please provide some data next time. Since I have no data I will use data and example from this link.

library(ggplot2)

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
  theme_minimal()

plot

Inside geom_text() vjust sets how "high" the text is. It is a little weird, because positive values mean that the text is lower and for negative values the text is higher. See here:

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=len), vjust=-1.5, color="black", size=3.5)+
  theme_minimal()

plot2

The variable used for label inside of geom_text does not have to be the variable that contains the y axis values. See the following example:

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                len=c(4.2, 10, 29.5),
                label= c("a", "b", "a"))

ggplot(data=df, aes(x=dose, y=len)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=label), vjust=1.6, color="white", size=3.5)+
 theme_minimal()

Upvotes: 2

Related Questions