Home > Back-end >  How to display all significant figures on labels when constructing bar charts using ggplot?
How to display all significant figures on labels when constructing bar charts using ggplot?

Time:11-16

I have constructed a bar chart using ggplot2 and I am displaying the values being graphed on each bar. My problem is that I cannot display the zeros that are trailing the values on each bar.

Here is my dataset:

data <- data.frame(product=c('product1',
                              'product2',
                              'product3',
                              'product4',
                              'product5',
                              'product6',
                              'product7',
                              'product8'),
                   test=c(0.60,
                          0.80,
                          0.50,
                          0.70,
                          0.40,
                          0.30,
                          0.20,
                          0.10))

The graph is generated with the following code:

ggplot(data, aes(product,test)) 
  geom_col() 
  geom_bar(stat="identity", col = "grey", fill="black") 
  coord_flip() 
  labs(title="Product comparisons") 
  theme(text=element_text(size=20)) 
  theme(axis.text.y=element_text(size=12)) 
  ylim(NA, 0.90) 
  geom_text(aes(label=round(test, digits=2)), nudge_y= -0.05, color="white", size = 6)

Result: enter image description here

Only the first decimal is displayed, but I need to display the zeroes after each of the labels. I tried to do this using the label=round(test, digits=2) command, but that did not fix it. What can be done to fix this?

CodePudding user response:

Try it!

ggplot(data, aes(product,test)) 
  geom_col() 
  geom_bar(stat="identity", col = "grey", fill="black") 
  coord_flip() 
  labs(title="Product comparisons") 
  theme(text=element_text(size=20)) 
  theme(axis.text.y=element_text(size=12)) 
  ylim(NA, 0.90) 
  geom_text(aes(label=format(round(test, digits = 2), nsmall = 2)), nudge_y= -0.06, color="white", size =3)
  • Related